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
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'.
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.