Alexander Solonik
Alexander Solonik

Reputation: 10230

How to replace entire string including html tags?

i am getting the following HTML from a textbox in laravel:

<p>Just a test</p>
<p>&nbsp;</p>
<p>Just a test</p>
<p>&nbsp;</p>
<p>Just a test</p>

Basically what i want to do is just remove all the &nbsp; and also all the <p>&nbsp;</p> , i am aware that using regex's to filter HTML is a bad idea , but in my case the scenario is limited to just there 2 options i mentioned above.

So i have the below PHP code:

$replaceNbsp = array('&nbsp' , '&nbsp;' , '<p>&nbsp;</p>' );
$blog_content = str_replace($replaceNbsp , ' ' , $request->blog_content);
return $blog_content;

But now intsead of removing the <p>&nbsp;</p> completely , i get the below output.

<p>Just a test</p>
<p> ;</p>
<p>Just a test</p>
<p> ;</p>
<p>Just a test</p>

How do i replace the HTML in the description too ??

Upvotes: 2

Views: 103

Answers (3)

Vivek m
Vivek m

Reputation: 29

can you try like this :

$replaceNbsp = array( '<p>&nbsp;</p>', '&nbsp;', '&nbsp' );
$blog_content = str_replace($replaceNbsp , ' ' , $request->blog_content);
return $blog_content;

Upvotes: 0

random_user_name
random_user_name

Reputation: 26150

In this case, there's nothing wrong with regular expressions:

$blog_content = preg_replace( '/<p>(&nbsp;)?<\/p>/g', '', $request->blog_content );

To stick with your original strategy, you need to reverse the order in the array to be order from most specific to least specific:

$replaceNbsp = array( '<p>&nbsp;</p>', '&nbsp;' , '&nbsp' );
$blog_content = str_replace($replaceNbsp , ' ' , $request->blog_content);

This way, it replaces the versions wrapped in <p> tag first, THEN the &nbsp; without <p> tags, etc.

Upvotes: 3

S. Imp
S. Imp

Reputation: 2895

You can use regex to get the paras containing just a non-breaking space and the newline char that follows them using this simple regex:

$blog_content = preg_replace('/<p>&nbsp;<\/p>\s*/', '', $request->blog_content);

Upvotes: 0

Related Questions