简体   繁体   中英

php / regex convert multiple paragraphs to one paragraph with line breaks

I want to convert a string like this

<p>one</p>
<p>two</p>
<p>three</p>

to this

<p>one<br>two<br>three</p>

(If it is only one paragraph tag then it would remain unchanged)

So I know the regex would basically just need to replace each </p><p> pair with a <br> , I could just str_replace() </p><p> with <br> but there will be possible line breaks or spaces between the closing and opening p tag.

So using regex, something like this. But this strips out 'two' (because it is between an ending and opening p tag). It also appears to break on new lines?

<?php
$string = '<p>one</p><p>two</p><p>three</p>';
$string2 = '<p>one</p>
<p>two</p>
<p>three</p>';
$pattern = '~</p>.*<p>~';
$replacement = '<br>';

echo preg_replace($pattern, $replacement, $string);
echo preg_replace($pattern, $replacement, $string2);

// Outputs "<p>one<br>three</p><p>one</p>" and "<p>one</p>
// <p>two</p>
// <p>three</p>"

Does anyone know how to fix that regex or know of a better method?

(I am using Wordpress in case there is some helper function)

Cheers! :)

Use

<?php
$string = '<p>one</p><p>two</p><p>three</p>';
$string2 = '<p>one</p>
<p>two</p>
<p>three</p>';
$pattern = '~</p>\s*<p>~u';
$replacement = '<br>';

echo preg_replace($pattern, $replacement, $string) . PHP_EOL. preg_replace($pattern, $replacement, $string2);

See proof .

Result:

<p>one<br>two<br>three</p>
<p>one<br>two<br>three</p>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM