Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove <p>&nbsp;</p> from end of string?

Tags:

string

regex

php

Maybe a newbie question:

I have a string like:

$string = '<p>this is what we need.</p><p>&nbsp</p>';

How can I remove the last characters, i.e. <p>&nbsp</p>, using PHP regex (not substr)?

I found a similar question here: remove <br>'s from the end of a string with solution: preg_replace('/(<br>)+$/', '', $string);

But changing this to: preg_replace('/(<p>&nbsp;</p>)+$/', '', $string); does not work.

It throws PHP Warning: preg_replace(): Unknown modifier 'p'

I guess I am missing some escaping? Of the <> or the slashes?

Thanks for your help.

like image 939
Avatar Avatar asked Dec 27 '22 03:12

Avatar


2 Answers

You are using the slash character as a regex delimiter and also as part of your regex (in the closing p tag) so you should escape it. So:

/(<p>&nbsp;</p>)+$/

should be

/(<p>&nbsp;<\/p>)+$/

And also it seems that this is not the kind of job for a regex, but it's your call.. str_replace or str_ireplace would do the job just fine

like image 194
mishu Avatar answered Jan 07 '23 17:01

mishu


Simple way you can do

$string = '<p>this is what we need.</p><p>&nbsp</p>';

$string = str_replace('<p>&nbsp</p>','',$string);
like image 21
Rakesh Singh Avatar answered Jan 07 '23 17:01

Rakesh Singh