匹配字符串单词的正则表达式模式


regex pattern to match words of a string

我有一个字符串数组(),我必须将它与单词的一部分进行比较,它必须是每个字符串中其中一个单词的开头!!

举个例子就好了:

array("hello word", "lovely child", "i am lost in paradise" ) 

我的测试词:"lo"

运行foreach和Regex后,我只需要:lovely child, i am lost in paradise

希望我说得很清楚!我有一个真正的问题与Regex:/

你能帮忙吗,谢谢

您可以将array_filter与正则表达式结合使用来实现此目的:

$array = array("hello word", "lovely child", "i am lost in paradise" );
$term = "lo";
// necessary in case $term contains characters with special meaning in a regex
$term = preg_quote($term, '/');
$results = array_filter(
             $array,
             function($el) use($term) {return preg_match('/'b'.$term.'/', $el);}
           );

正则表达式使用词边界锚来确保搜索词出现在单词的开头。

另一个

$array = array("hello word", "lovely child", "i am lost in paradise" );
$find='lo';
print_r(preg_grep('/'b'.$find.'/', $array));