PHP - 搜索特定Word数组的字符串并与可选+或 - 匹配

时间:2014-01-05 05:41:56

标签: php arrays word match

我需要在字符串中搜索特定单词并将匹配作为变量。我在数组中有一个特定的单词列表:

$names = array ("Blue", "Gold", "White", "Purple", "Green", "Teal", "Purple", "Red");

$drag = "Glowing looks to be +Blue.";

$match = "+Blue";

echo $match

+Blue

我需要做的是使用$drag搜索$names并找到与+-选项匹配的内容,并$match成为结果

2 个答案:

答案 0 :(得分:2)

通过将数组的术语与|结合使用,并在开头添加可选的[-+]来构建正则表达式:

$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"

如果您想确保只匹配+Blue而不是+Bluebell,则可以将字边界匹配\b添加到正则表达式的开头/结尾。

如果要查找所有单词的所有实例,请改用preg_match_all

答案 1 :(得分:0)

是的,如果您使用prey_match和一些正则表达式逻辑,则可以。

// Set the names array.
$names_array = array ("Blue", "Gold", "White", "Purple", "Green", "Teal", "Purple", "Red");

// Set the $drag variable.
$drag = "Glowing looks to be +Blue.";

// Implode the names array.
$names = implode('|', $names_array);

// Set the regex.
$regex = '/[-+]?(' .  $names . ')/';

// Run the regex with preg_match.
preg_match($regex, $drag, $matches);

// Dump the matches.
echo '<pre>';
print_r($matches);
echo '</pre>';

输出结果为:

Array
(
    [0] => +Blue
    [1] => Blue
)