tags:

views:

58

answers:

2

Hi,

I have a variable, $var, that contains a string of characters, this is a dynamic variable that contains the values from inputs.

$var could be 'abc', or $var could be 'blu',

I want to match the string inside variable against an array, and return all the matches.

$array = array("blue", "red", "green");

What is the correct syntax for writing the code in php, my rough code is below

$match = preg_grep($var, $array); (incorrect syntax of course)

I tried to put quotes and escape slashes, but so far no luck. Any suggestion?

TIA

+2  A: 

Try

$match = preg_grep('/' . $var . '/', $array);

Patterns for PCREs must be enclosed in delimiters.

Of course you have to adjust the pattern, depending on your needs. E.g. if you want to match all strings in the array that start with the string in $var you have to change it to:

$match = preg_grep('/^' . $var . '/', $array);

And so on...

Felix Kling
Thanks, that worked
Jamex
+1  A: 
$var = 're';

$array = array("blue", "red", "green");

$pattern = '/'.$var.'/';

$matches = preg_grep($pattern, $array);

echo '<pre>';
var_dump($matches);
echo '<pre>';

returns

array(2) {
  [1]=>
  string(3) "red"
  [2]=>
  string(5) "green"
}
Mark Baker
Thanks, it works, I am grateful.
Jamex
and thanks for the <pre> tags example, I have been using print_r for debug and have been wondering how the online examples for arrays are well formatted.
Jamex
re. <pre> tags... the second should have been </pre> :-( <blush>
Mark Baker