PHP - Search String for a Specific Word Array and Match with an Optional + or -

假如想象 提交于 2019-12-06 09:46:00

问题


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.


回答1:


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);

Output:

string(5) "+Blue"

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.

If you want to find all instances of all words, use preg_match_all instead.




回答2:


Yes, you can if you use prey_match and some regex logic.

// 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>';

The output is:

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


来源:https://stackoverflow.com/questions/20930558/php-search-string-for-a-specific-word-array-and-match-with-an-optional-or

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!