简体   繁体   中英

PHP preg_replace - String Begins With Forward Slash

Trying to use preg_replace to find strings that begin and end with a forward-slash, for example "/Harry/" . (has to be preg_replace)

I also need to ignore case and ensure it is an individual word. So far I have the following but I am having little luck getting it to work:(

$old_words[0] = '/\b\/Harry\/\b/i';

$new_words[0] = 'Wizard';

$chat = preg_replace($old_words, $new_words, $chat);

Should your problem really just be the word boundaries \b , then you could try some auxiliary assertions instead:

$old_words[0] = '#(?<!\w)/Harry/(?!\w)#i';

That basically ensures that no letters can occur before or after the slashes.

If you just want to replace single words, it is not necessary to use preg_replace . Use str_ireplace (for case-insensitive replacement) instead. However, you can use other chars than / as delimiter for your regular expression: # , ~ , …

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