Match the exact word with any regular expression character

How to combine the exact word contains any special character?

$string = 'Fall in love with #PepsiMoji! Celebrate #WorldEmojiDay by downloading our keyboard @ http://bit.ly/pepsiKB & take your text game up a notch. - teacher'; preg_match("/\b#worldemojiday\b/i",$string); //false 

I want to combine the exact word containing any character. For example, if I want to combine the word “load” on this line, it should return false

 preg_match("/\bdownload\b/i",$string); //false 

But when I search for a download, it should return true.

thanks

+6
source share
2 answers

The problem is the \b word boundary before the non-word character # . \b cannot match the position between two characters other than a word (or between two words), so you won’t get a match.

The solution is to remove the first \b or use \b (a non-phrase between two words or two nonsmooth characters) instead.

 \B#worldemojiday\b 

or

 #worldemojiday\b 

See demo (or this one )

Note that \b also matches at the beginning of a line.

Here is a way to dynamically create a regular expression by adding word boundaries only where necessary:

 $srch = "žvolen"; $srch = preg_quote($srch); if (preg_match('/\w$/u', $srch)) { $srch .= '\\b'; } if (preg_match('/^\w/u', $srch)) { $srch = '\\b' . $srch; } echo preg_match("/" . $srch . "/ui", "žvolen is used."); 
+3
source

How about using hits :

 (?<!\w)#WorldEmojiDay(?!\w) 

This ensures that there is no word character before or after the line. See test in regex101

+1
source

All Articles