Reputation: 10230
i am getting the following HTML from a textbox in laravel:
<p>Just a test</p>
<p> </p>
<p>Just a test</p>
<p> </p>
<p>Just a test</p>
Basically what i want to do is just remove all the
and also all the <p> </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(' ' , ' ' , '<p> </p>' );
$blog_content = str_replace($replaceNbsp , ' ' , $request->blog_content);
return $blog_content;
But now intsead of removing the <p> </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
Reputation: 29
can you try like this :
$replaceNbsp = array( '<p> </p>', ' ', ' ' );
$blog_content = str_replace($replaceNbsp , ' ' , $request->blog_content);
return $blog_content;
Upvotes: 0
Reputation: 26150
In this case, there's nothing wrong with regular expressions:
$blog_content = preg_replace( '/<p>( )?<\/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> </p>', ' ' , ' ' );
$blog_content = str_replace($replaceNbsp , ' ' , $request->blog_content);
This way, it replaces the versions wrapped in <p>
tag first, THEN the
without <p>
tags, etc.
Upvotes: 3
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> <\/p>\s*/', '', $request->blog_content);
Upvotes: 0