我需要在字符串中搜索特定单词并将匹配结果作为变量。我在数组中有一个特定的单词列表:
$names = array ("Blue", "Gold", "White", "Purple", "Green", "Teal", "Purple", "Red");
$drag = "Glowing looks to be +Blue.";
$match = "+Blue";
echo $match
+Blue
我需要做的是搜索$drag
与$names
并找到与选项匹配的内容+
or -
性格和拥有$match
成为结果。
通过将数组的项与|
,并添加一个可选的[-+]
在开始时:
$names = array ("Blue", "Gold", "White", "Purple", "Green", "Teal", "Purple", "Red");
$drag = "Glowing looks to be +Blue.";
$pattern = '/[-+]?(' . join($names, '|') . ')/';
$matches = array();
preg_match($pattern, $drag, $matches);
$matches = $matches[0];
var_dump($matches);
Output:
string(5) "+Blue"
如果你想确保你只匹配+Blue
并不是+Bluebell
,您可以添加单词边界匹配,\b
,到正则表达式的开头/结尾。
如果您想查找所有单词的所有实例,请使用preg_match_all
反而。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)