I’m trying to check if the given string contains words that are not listen in my $allowed array. If it does I want them replaced with “”.
So let’s say my string contains “Hello World” and “World” is not in my allowed words it should replace “World” with “”.
Another issue I have is that my current implementation is case sensitive.
$string = "Test new world"; $allowed = array('hello', 'test'); if(in_array($string, $allowed)) { } else { // Return false or Replace with "" }
Advertisement
Answer
I can answer partially by showing you how to keep word boundaried words, removing everything else from the string:
<?php $input = 'hotdogs are food, not actual HOT dogs. The latter being dog animals that are hot.'; $words = [ 'hot', 'dog' ]; $regex = '@b(' . implode($words, '|') . ')b@i'; $output = ''; if(preg_match_all($regex, $input, $matches)) $output = implode($matches[0]); print $output;
Output:
HOTdoghot