【问题标题】:Filter array to keep values containing the search word using word boundaries过滤数组以使用单词边界保留包含搜索词的值
【发布时间】:2022-01-18 21:29:00
【问题描述】:

我知道以前有人问过这类问题,我也看到了那些有效的答案。但是,当搜索字符串和数组值的其余部分之间没有空格时,它不起作用。这是我的代码-

$example = array ( 'ext_03.jpg', 'int_01_headlight.jpg');
$searchword = 'int_';
$matches = array_filter($example, function($var) use ($searchword) {
    return preg_match("/\b$searchword\b/i", $var);
});
echo array_values($matches)[0];`

$example 数组中的最后一个值没有任何空格,此代码不起作用。但是,如果我在int_ 之后放置空格,它会起作用。但即使没有空间,我也需要它工作(也应该在有空间的情况下工作)。我怎样才能做到这一点?

【问题讨论】:

  • 为什么不使用strpos函数呢?或者你的$searchword 可以是正则表达式?

标签: php arrays regex filtering word-boundary


【解决方案1】:

解决办法如下:

$example = array ( 'ext_03.jpg', 'int_01_headlight.jpg');
$searchword = 'int_';
$matches = array_filter($example, function($var) use ($searchword) { return 
preg_match("/\b$searchword/i", $var); });
var_dump($matches);

删除第二个 \b :模式中的 \b 表示单词边界

文档:http://php.net/manual/en/function.preg-match.php

编辑:

更好的方法是使用 \A :字符串的开头

$example = array ( 'ext_03.jpg', 'int_01_headlight.jpg', 'ext_ int_01_headlight.jpg');
$searchword = 'int_';

// Return 2 results (wrong way)
$matches = array_filter($example, function($var) use ($searchword) { return preg_match("/\b$searchword/i", $var); });
var_dump($matches);

// Return 1 result
$matches = array_filter($example, function($var) use ($searchword) { return preg_match("/\A$searchword/i", $var); });
var_dump($matches);

【讨论】:

    【解决方案2】:

    当您希望使用正则表达式过滤数组时,在array_filter() 中调用preg_match() 不是最佳选择。

    最合适的电话是preg_grep()

    试试这样的:

    $example = preg_grep('~\bint_~', $example);
    

    如果您的逻辑需要,您可以在 _ 之后使用字符类扩展模式。

    但如果您只对第一场比赛感兴趣 ([0]),那么您不妨运行 foreach()preg_match()break

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-26
      • 2022-11-28
      • 2016-02-26
      • 1970-01-01
      • 2014-12-11
      • 1970-01-01
      • 1970-01-01
      • 2023-03-09
      相关资源
      最近更新 更多