March 25, 2012

PHP regular expression split

Question by Matthew Underwood

I will make this quick and simple

I have a query and I want to split it so that it returns an array with words after the : symbol. This is what I have so far and it does as expected but returns the whole string before the matched needle. I just want the array to contain words after the : symbol.

<?php  $arr = preg_split('/[:]/', $query, 0); 

   print_r($arr);

 ?>

This returns

    Array
(
    [0] => SELECT user_name FROM test WHERE user_name = 
    [1] => user_name
)

using this query

“SELECT user_name FROM test WHERE user_name = :user_name”

thanks for any help

Answer by Taylor Dondich

Try this:

preg_match_all("/:(w+)/", $string, $matches);

By doing this, all your elements that are after a : will be in $matches[1] sub-array. I’m assuming you want to handle SQL statements with multiple named parameters. So for example:

SELECT user_name FROM test WHERE user_name = :user_name and last_name = :last_name

Will result in $matches being:

array(2) {
  [0]=>
  array(2) {
    [0]=>
    string(10) ":user_name"
    [1]=>
    string(10) ":last_name"
  }
  [1]=>
  array(2) {
    [0]=>
    string(9) "user_name"
    [1]=>
    string(9) "last_name"
  }
}

Answer by Starx

You might want to use, preg_match() for this

$query = "SELECT user_name FROM test WHERE user_name = :user_name";
preg_match('/:(w+)/', $query, $matches);
echo $matches[1]; //gives your user_name

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!