ytdm
ytdm

Reputation: 1169

php replace paragraph to newline

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.

Upvotes: 4

Views: 8874

Answers (4)

Rubain
Rubain

Reputation: 81

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);

Upvotes: 8

ytdm
ytdm

Reputation: 1169

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);

Upvotes: 4

v2solutions.com
v2solutions.com

Reputation: 1439

<?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.

Upvotes: 0

David Ansermot
David Ansermot

Reputation: 6112

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.

Upvotes: 0

Related Questions