I have a variable, $var
, that contains a string of characters, this is a dynamic variable that contains the values from inputs.
我有一个变量$var,它包含一个字符串,这是一个动态变量,它包含输入的值。
$var
could be 'abc'
, or $var
could be 'blu'
,
$var可以是abc, $var可以是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
用php编写代码的正确语法是什么,我的大致代码如下
$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 个解决方案
#1
1
$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"
}
#2
2
Try
试一试
$match = preg_grep('/' . $var . '/', $array);
Patterns for PCREs must be enclosed in delimiters.
PCREs的模式必须包含在分隔符中。
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:
当然,您必须根据需要调整模式。例如,如果你想匹配数组中以$var中的字符串开头的所有字符串,你必须将其更改为:
$match = preg_grep('/^' . $var . '/', $array);
And so on...
等等……
#1
1
$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"
}
#2
2
Try
试一试
$match = preg_grep('/' . $var . '/', $array);
Patterns for PCREs must be enclosed in delimiters.
PCREs的模式必须包含在分隔符中。
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:
当然,您必须根据需要调整模式。例如,如果你想匹配数组中以$var中的字符串开头的所有字符串,你必须将其更改为:
$match = preg_grep('/^' . $var . '/', $array);
And so on...
等等……