Reputation: 61
I have a variable that I'm trying to check whether it contains a set of specific words. If it contains any of those words, they should be removed.
The code I've tried is:
$title = 'Help my title';
$array = array("help","test","trying");
if(0 < count(array_intersect(explode(' ', strtolower($title)), $array))){
$titlenew = str_replace($array, "", $title);
}
My expectation is that the above would return:
my title
If it could be case insensitive too, that would be great - although it's not my priority.
Thanks
Upvotes: 4
Views: 6545
Reputation: 2289
I'd probably do this with regular expressions:
$str = preg_replace('/\b(word1|word2)\b/i', '', $str);
\b
is a word boundary: https://www.php.net/manual/en/regexp.reference.escape.php
Upvotes: 2
Reputation: 10132
You need str_ireplace()
:
$title = 'Help my title';
$array = array("help","test","trying");
echo str_ireplace($array, '', $title); // my title
Upvotes: 4