griffen Posted December 14, 2006 Share Posted December 14, 2006 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. Quote Link to comment Share on other sites More sharing options...
c4onastick Posted December 15, 2006 Share Posted December 15, 2006 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'. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.