Reputation: 127
I need to replace all:
<p> </p>
<p> </p>
<p> </p>
with
<p> </p>
using regex how would i go about doing this?
Upvotes: 0
Views: 826
Reputation: 10169
If this is a well bounded case you can use preg_replace()
to achieve that with:
RegEx: (<p> <\/p>\s*)+
Replacement: \1
Explained demo: http://regex101.com/r/vB5sZ0
Upvotes: 1
Reputation: 4456
If you don't want to use regex, use str_replace
.
Replace all <p> </p><p> </p>
with one and do it until no change is made.
$input2 = $input_text;
$end = false;
while(!$end){
$temp_text=str_replace("<p> </p><p> </p>","<p> </p>", $input2);
if($temp_text == $input2){
$end = true;
}
else{
$input2 = $temp_text;
}
}
In the line with str_replace()
you might need to add a new line character (\n
) and/or line feed (\r
).
Upvotes: 0
Reputation: 810
Here you go :
"<p> </p>\n<p> </p>\n<p> </p>"
.replace(/(<p> <\/p>\n?)+/, "<p> </p>");
Upvotes: 0
Reputation: 32827
You should use an html parser instead of regex.
But if the p
tag is not nested you can use this regex
/<p> </p>/
Upvotes: 0
Reputation: 27040
Despite some comment correctly pointing out that parsing HTML using regex's is dangerous, in controlled environments or when parsing isn't necessary (your case I believe, as you seem to only want to replace some stuff) I consider it to be the most optimal solution (despite not being perfect).
Either way, if I understood your question correctly you want to replace multiple duplicates with a single instance? In that case it can be simply achieved by a regex along the lines of:
"<br><br>a<br><br><br>b".replace(/(<br>){2,}/g, '<br>');
That example is in javascript (as I could test it out from the browser console), but the regex and basic concept is the same in php: you match two or more instances of the string you're interested in and replace it with a single instance.
Upvotes: 0