00-BBB
00-BBB

Reputation: 856

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! :)

Upvotes: 2

Views: 214

Answers (1)

Ryszard Czech
Ryszard Czech

Reputation: 18611

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>

Upvotes: 1

Related Questions