1

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);

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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: #, ~, …

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.