0

I have a string of html with consists of many <p> tags and other html tags.

How can I replace <br /> tags between <p> and </p> tag, so that it become multiple paragraphs using regex?

(I need to replace in <p> tag only, not in other tags)

Sample source:

<p> This is a paragraph without line break</p>
<p> This is a paragraph with <br /> line <br /> break</p>

Sample output:

<p> This is a paragraph without line break</p>
<p> This is a paragraph with </p><p> line </p><p> break</p>
vences
  • 153
  • 7
  • Would you like to write regexp with php? Or in any other language? – KlapenHz Jul 31 '17 at 08:49
  • Suggest to use [str_replace](http://php.net/manual/en/function.str-replace.php) instead of preg_replace function. Or You need to replace
    only inside

    ?
    – A.Mikhailov Jul 31 '17 at 08:50
  • 1
    From your question it seems that you don't want to replace the `
    ` if it is not between `

    ` tags - but your sample doesn't cover that.

    – Sebastian Proske Jul 31 '17 at 08:52
  • Sorry, I need to replace
    only inside

    only, not in other tags. Forgot to mention inside question.
    – vences Jul 31 '17 at 08:55
  • 1
    "using regex" — Why do you have this requirement? [Regular expressions are not well suited to manipulating HTML. There are better ways](https://stackoverflow.com/a/1732454/19068). – Quentin Jul 31 '17 at 09:00
  • If not using regex, any better suggestion? sorry I'm still not that familiar with php – vences Jul 31 '17 at 09:15

2 Answers2

2
<?php

$string = '<p> This is a paragraph without line break</p>
text <br /> without p <br />
<p> This is a paragraph with <br /> line <br /> break</p>
<p>aaaa <br /></p>
dsa<br />
<p><br /></p>';

// Start non-greedy search for text in paragraphs
preg_match_all('/<p>.*?<\/p>/im', $string, $matches);

$matches = $matches[0];

// for each match replace <br /> inside text
foreach ($matches as $key => $match) {
    $replaced[$key]['initial'] = $match;
    $replaced[$key]['replaced'] = str_replace('<br />', '</p><p>', $match);
}

// replacing initial parts of text with replaced parts
foreach ($replaced as $key => $replacePair) {
    $string = str_replace($replacePair['initial'], $replacePair['replaced'], $string);
}

print_r ($string);

sandbox code

A.Mikhailov
  • 466
  • 4
  • 9
-1

Use PHP function str_replace. It'll replace all "br" tags. Use it like this:

$result = str_replace('<br />', '', $input);
Daniele Fois
  • 121
  • 6
  • 1
    use this. dont use regex with html, it's not healthy or fun. See here. https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags – delboy1978uk Jul 31 '17 at 08:51
  • This doesn't meet the "Only inside p elements" restriction that the question imposes. This doesn't meet the requirement to turn line breaks into paragraph breaks that the question imposes. It is also very fragile and depends on the very specific Appendix C form of the br element. – Quentin Jul 31 '17 at 09:01