I want to remove words which are surrounded by special characters using preg_replace()
:
$product_name = 'Choose a : giFt ,';
$word = 'gift';
$regex = '/[-:,]?\b'.$word.'\b[-:,]?/i';
if(preg_match($regex, $product_name))
{
$str = preg_replace($regex, "", trim($product_name));
}
echo $str;
output:
Choose a : ,
It works fine if there is no space means if my string is "Choose a :giFt,".
My expected output is
Choose a
You must try this :
$regex = '`:([^>]+),`';
But you must clean your code too, you don't need $regex and $regex_p
Just add spaces in your character class:
$regex = '/[-:,\s]*\b'.$word.'\b[-:,\s]*/i';