Jump to content

Searching for whole words


griffen

Recommended Posts

I'm trying to use preg_match to find whole words in a string. The problem is that the words that I am searching for can appear at the end of the string. For example:

"great new hardware K800"

or

"great new hardware K800i"

Further they can appear in a string in the middle:

"great new hardware K800i in blue"

or

"great new hardware K800 in blue"

If I am searching for K800, in some strings that feature K800i they will be returned as a match. How do I go about searching for the whole word K800 and return the correct match in both situations?

Thanks.
Link to comment
https://forums.phpfreaks.com/topic/30570-searching-for-whole-words/
Share on other sites

Adding word boundaries to your regex will solve this problem.

[code]$strings = "great new hardware K800\ngreat new hardware K800i\ngreat new hardware K800i in blue\ngreat new hardware K800 in blue";

preg_match_all( '/\bK800\b/', $strings, $matches );

print_r($matches);
[/code]
The '\b' metacharacter matches a word boundary (it behaves similarly to a positive look ahead or look behind for a space, punctuation, etc.). This will only match the exact string 'K800', since 'K800i' doesn't have a word boundary after the second '0'.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.