doushi4956 2017-01-17 10:52
浏览 155
已采纳

php preg_grep在给定正则表达式在匹配单词之间有空格时不起作用

I am trying to match a word with list of tag names in an array using preg_grep

$tagOptArray = array("Corporate", "Exporters", "Buyers", "News", "Apparel","Aquarium Fish", "Boat and Ship Building");
$subBlockTag = "Boat";

$tag = preg_grep('/' . $subBlockTag . '[.]*/i', $tagOptArray);

var_dump($tag);

this outputs the following result.

array(1) { [6]=> string(22) "Boat and Ship Building" }

But when $subBlockTag = "Boat Building"; this returns an empty array which is not expected since it should match with "Boat and Ship Building" in the tags array.

EDIT

following are the possible tags that can be assigned for $subBlockTag

$subBlockTag = "Boat Building";
$subBlockTag = "Ornamental Fish";
$subBlockTag = "Fish";
$subBlockTag = "Fruits and Vegetables";
$subBlockTag = "Diamond and Jewellery";
  • 写回答

2条回答 默认 最新

  • drcmg28484 2017-01-17 11:13
    关注

    If you have regular words separated with spaces in the $tagOptArray and you need to match items that contain the words in the same order, you may replace all spaces with .* and use your approach:

    $tagOptArray = array("Corporate", "Exporters", "Buyers", "News", "Apparel","Aquarium Fish", "Boat and Ship Building");
    $subBlockTag = "Boat Building";
    $tag = preg_grep('/' .  preg_replace("~\s+~", ".*", trim($subBlockTag)) . '/is', $tagOptArray);
    print_r($tag);
    

    See the PHP demo.

    I suggest to also use trim($subBlockTag) to avoid having .* at leading/trailing positions, especially in the leading position to avoid performance issues. This might be slow if you have very long texts to handle.

    To find a match when all the space separated words are present in the string, you need to construct a regex with positive lookaheads anchored at the start:

    $tagOptArray = array("Corporate", "Exporters", "Buyers", "News", "Apparel","Aquarium Fish", "Boat and Ship Building");
    $subBlockTag = "building boat";
    $tag = preg_grep('/^(?=.*' .  implode(")(?=.*", preg_split("~\s+~", trim($subBlockTag))) . ')/is', $tagOptArray);
    print_r($tag);
    

    See another PHP demo, and here is a regex demo.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?