2

I'm fairly new to PHP and struggling to understand the best way to do this. I have an array:

$colours= array('Yellow', 'Red', 'Blue');

I now need to check a string against this array and if one of the colors exists in the string we then need to output the result into a new variable. Here's a sample string:

$string= "Black & Aztec Blue";

So in this case the desired output would be "Blue". Or, as suggested below both values could be saved in a second array? Has anyone done something like this before?

All help appreciated.

11
  • 1
    You could explode on spaces then iterate through each value. If you had two found values would you want both or just the first one? Commented Oct 6, 2015 at 15:57
  • @chris85 great idea, but some of the strings may contain nospaces or slashes instead of spaces etc... Very messy data! eg. "Red/Tarmac Black" ideally this would be Red as Black is a secondary colour. I guess both would be good. Perhaps as another array? Commented Oct 6, 2015 at 15:59
  • 2
    php.net/strpos php.net/foreach Commented Oct 6, 2015 at 16:01
  • Do you know the list of ALL possible separation characters? Commented Oct 6, 2015 at 16:04
  • Oh, yea @MarcB's idea is better. Iterate through your colors and use strpos on the string for matches. Commented Oct 6, 2015 at 16:05

1 Answer 1

2

Create a regexp that matches any of the words using alternation |.

$regexp = '/\b(' . implode('|', $colours) . ')\b/'; // $regexp = '/\b(Yellow|Red|Blue)\b/'
if (preg_match($regexp, $string, $match)) {
    $found_word = $match[0];
}

\b matches word boundaries, so this will not match if the strings are adjacent like BlackBlue. Take them out if you want to match the colours in this case.

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

8 Comments

Will this find if two words are connected like BlackBlue Red?
No. The \b operator only matches at word boundaries.
Thanks for this @Barmar. I might be able to hack this to work. Is there a way of getting it to work regardless of case? As some of the words are uppercase and mixed case.
Add the i modifier to the regexp.
Maybe before asking any more questions, you should brush up on the documentation of using regexp in PHP?
|

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.