Hi all im trying to build a regular expression which will sustain the following criteria.
Word to be censored in this example “view”.
Character to be used after censor: “%”, since “*” mess up my post formatting.
Examples of word use:
view
views
preview
I went to see the great view
The view was great wasn’t it.
Example after word censor:
%%%%
views
preview
I went to see the great %%%%
The %%%% was great wasn’t it.
Here is some code I have:
$string = preg_replace_callback('/\s*'. preg_quote($word, '\\') .'\s*/is', 'bbcode_callback_censored', $string);
Trouble is this matches everything right now since i use “*” in the regex ater “\s”. Any ideas what I could do to fulfill my criteria?
Don’t match for whitespace, use a word boundary
Try
See it here on Regexr
You just need to make sure that the content of
$worddoes not start or end with a non word character, then the word boundary will not work.\bis a word boundary. It matches on a change from a word character (as defined in\w) to a non word character as defined in\W, or the other way round.Alternative: whitespace boundary
If you don’t like the word boundary because it is possible that your word to replace starts or end with non word characters like “#view”, define your own “whitespace boundary”, e.g. like this:
See it here on Regexr
Would look in your code like this
(?<=^|\s)will match if there is the Start of the String or whitespace before(?=$|\s)will match if there is the end of the String or whitespace ahead