4

how to replace <p>hello</p> <p>world</p> to hello<br />world <br />

I've tried searching on stack but there is no matched result.

ytdm
  • 1,069
  • 1
  • 12
  • 15

4 Answers4

8

You could do this by using str_replace() function.

For instance:

$string = "<p>hello</p> <p>world</p>";
$string = str_replace('<p>', '', $string);
$string = str_replace('</p>', '<br />' , $string);
hadi aj
  • 160
  • 10
Rubain
  • 81
  • 3
4

I try this myself and get what I expected

$pattern = '/<p>(\w+)\<\/p>/';
$subject = '<p>hello</p><p>world</p>';
$replacement = '${1}<br/>';
$out = preg_replace($pattern, $replacement, $subject);

I just wonder which is better regex or str_replace

I wrote a better solution, hope everybody can see it helpful and maybe improve it

$pattern = '/<p(.*?)>((.*?)+)\<\/p>/';
$replacement = '${2}<br/>';
$subject = 'html string';
$out = preg_replace($pattern, $replacement, $subject);
ytdm
  • 1,069
  • 1
  • 12
  • 15
0

Use this to prevent breaking the first and last <p></p> :

$string = str_replace($string, '</p><p>', '');

But if a space comes between the tags, it won't work.

David Ansermot
  • 6,052
  • 8
  • 47
  • 82
0
<?php
$str = '<p>hello</p> <p>world</p>';
$replaceArr = array('<p>', '</p>', '</p> <p>');
$replacementArr = array('', '', '<br />');
$str = str_replace($replaceArr, $replacementArr, $str);
echo $str;
?>

Try above code.

v2solutions.com
  • 1,439
  • 9
  • 8