Search code examples
phpregexdompreg-replacehtml-manipulation

Wrap text with <p> until the first <p> appears


How can I wrap from the beginning of the text in a string until the first <p> appears? For example, If the string is

this is some <b>text</b><p>Beginning of a paragraph</p>

I want

<p>this is some <b>text</b></p><p>Beginning of a paragraph</p>

Any way to achieve this? Thanks!


Solution

  • Perhaps try

    $str = '<p>' . preg_replace('#<p>#', '</p>\0', $str, 1);