Match a list of words in a string with space inbetween characters



Say that I have a string that looks like this:

Give me your xw al l et now!

And a list of banned words:

wallet, banana, potato

How would I write the regular expression to catch any of those words? Even with spaces inbetween characters.


2 Answers: 

This code will do the work:

foreach($banned as $word) {
    $chars = str_split($word);
    $pattern = implode(' ?', $chars);
    $check = preg_match('/'.$pattern.'/i', $text);

$banned is the array of forbidden words

$text is the text you are validating for forbidden words

And $check marks if given banned word is found, and depending on your logic you want to achieve, use this variable in appropriate way for you.

Simple way to catch any word (without space) :

function censorship($bannedwords, $sentence) {
    foreach($bannedwords as $word) $sentence = str_replace($word, '****', $sentence);
    return $sentence;

$bannedwords = ['banana', 'potato'];
echo censorship($bannedwords, 'Every banana is a potato');
// Output : Every **** is a ****