Reputation: 79
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
Upvotes: 2
Views: 134
Reputation: 816810
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...
Upvotes: 2
Reputation: 212452
$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"
}
Upvotes: 1