The following will find the first row, replace the 'blue' word on that line with nothing (remove it), strip tags and remove leading/trailing space.
- Will only remove whole words, e.g. not 'blue' in 'blues'
- Will not remove word from following lines if not found in first line
- Will not strip tags from following lines
Code:
$text = "<p></p><br/>I have new blue car
I have new <b>red<b> and blue cars";
$word = 'blue';
$text = preg_replace_callback(
'/.*$/m', // Match single line
function ($matches) use ($word) {
// Remove word (\b = word boundary), strip tags and trim off whitespace
return trim(
strip_tags(
preg_replace('/\b' . $word. '\s*\b/', '', $matches[0])
)
);
},
$text,
1 // Match first line only
);
echo $text, PHP_EOL;
Output:
I have new car
I have new <b>red<b> and blue cars