将变量内的字符串与数组进行匹配的正确语法

发布于 2024-09-03 16:36:14 字数 432 浏览 3 评论 0原文

我有一个变量 $var,其中包含一个字符串,这是一个包含输入值的动态变量。

$var 可以是 'abc',或者 $var 可以是 'blu'

我想匹配字符串内部变量针对数组,并返回所有匹配项。

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

在 php 中编写代码的正确语法是什么,我的粗略代码如下

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

我尝试添加引号和转义斜杠,但到目前为止还没有运气。有什么建议吗?

TIA

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

山田美奈子 2024-09-10 16:36:14

尝试

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

PCRE 模式 必须包含在 分隔符

当然,您必须根据您的需要调整模式。例如,如果您想匹配数组中以 $var 中的字符串开始的所有字符串,则必须将其更改为:

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

依此类推...

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...

野却迷人 2024-09-10 16:36:14
$var = 're';

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

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

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

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

回报

array(2) {
  [1]=>
  string(3) "red"
  [2]=>
  string(5) "green"
}
$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"
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文