简体   繁体   中英

How to use PHP to search a string for words starting/ending with special regular expression characters?

I am using PHP to find out whether a string, which starts with a special regular expression character, occurs as a word in a text string. This is the PHP code:

$subject = " hello [hello [helloagain ";
$pattern = preg_quote("[hello");
if (preg_match("/\b" . $pattern  . "\b/", $subject, $dummy)) { 
    echo "match";
} else {
    echo "no match";
}

The pattern starts with character [, hence, preg_quote() is used to escape it. There is an instance of [hello as a word in the subject so there should be one match, but the above preg_match() returns no match. I think the reason is that in the subject a special character is not recognized as the start or end of a word, but I can't think of any way round this, any ideas? Thank you.

If I understand the question correctly, you could just use strpos() with a leading space to separate words:

$subject = " hello [hello [helloagain ";
$pattern = " [hello";

if(strpos($subject, $pattern) !== FALSE)
  // ...
else
  // ...

I think that not using reg-ex here is actually a better method since you are looking for special reg-ex chars, and they do not have to be escaped if you use strpos() .

It would take some modification to be right in all cases, but this worked when I tried it.

You are correct that a word boundary will not match between a space and a [ symbol.

Instead of using a word boundary you can explicitly search for spaces (and other separators such as commas and periods if you wish) before and after the word:

if (preg_match("/(\s|^)" . $pattern  . "(?=\s|$)/", $subject, $dummy)) { 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM