2

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.

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

7 Comments

Is there a way for the result to be just +Blue by itself instead of +Blue and Blue?
Err, yes, take $matches[0]. Matches contains the full match, and then any sub-groups, and my regex happens to use one sub-group around the search words. See update.
"Warning: preg_match() expects parameter 2 to be string" I guess this must be due to the old PHP version GoDaddy has installed.
No, it's because you're not giving it a string. Your second parameter, $drag in my example, has to be a string. I'd wager that's completely consistent with every version of PHP since preg_match was introduced.
Not sure what it was but it is working fine now after re-pasting the code. Thanks.
|
0

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
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.