PHP - 搜索字符串为一个特定的单词阵列,并匹配一个可选的+或 - [英] PHP - Search String for a Specific Word Array and Match with an Optional + or -
问题描述
我需要寻找一个字符串一个特定的词,并有比赛是一个变量。我有话的具体列表中的数组:
I need to search a string for a specific word and have the match be a variable. I have a specific list of words in an array:
$names = array ("Blue", "Gold", "White", "Purple", "Green", "Teal", "Purple", "Red");
$drag = "Glowing looks to be +Blue.";
$match = "+Blue";
echo $match
+Blue
我需要做的是搜索 $拖
与 $名称
并找到匹配的选项 +
或 -
字符,并有 $匹配
成为结果
What I need to do is search $drag
with the $names
and find matches with an option +
or -
character and have $match
become the result.
推荐答案
与加入阵列的条款建立一个正规的前pression |
,并添加可选的 [ - +]
开头:
Build a regular expression by joining the terms of the array with |
, and adding an optional [-+]
at the beginning:
$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);
输出:
string(5) "+Blue"
如果你想确保你只匹配 +蓝
,而不是 +风信子
,您可以添加单词边界比赛中, \\ b
,以正则表达式的开始/结束。
If you want to insure that you match only +Blue
and not +Bluebell
, you can add word boundary matches, \b
, to the beginning/end of the regex.
如果你想找到的所有单词的所有实例,使用 preg_match_all
代替。
If you want to find all instances of all words, use preg_match_all
instead.
这篇关于PHP - 搜索字符串为一个特定的单词阵列,并匹配一个可选的+或 - 的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!