1

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!

ggorlen
  • 44,755
  • 7
  • 76
  • 106
user2335065
  • 2,337
  • 3
  • 31
  • 54
  • Yes, there is a way to achieve this, but it's good form to post what you've tried so that the question is [on topic](https://stackoverflow.com/help/on-topic). See [mcve]. – ggorlen Jun 06 '19 at 17:49

3 Answers3

2

Perhaps try

$str = '<p>' . preg_replace('#<p>#', '</p>\0', $str, 1);
jspcal
  • 50,847
  • 7
  • 72
  • 76
0

Maybe use something like this:

str_replace(".","</p>.<p>", $myText);
user2450639
  • 196
  • 1
  • 14
0

If our inputs would be just as simple as the one in the question, we would start with a simple expression and a preg_replace:

$re = '/(.+?)(<p>.+?<\/p>)/m';
$str = 'this is some <b>text</b><p>Beginning of a paragraph</p>';
$subst = '<p>$1<\/p>$2';

$result = preg_replace($re, $subst, $str);

echo $result;

Demo

Output

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

RegEx Circuit

jex.im visualizes regular expressions:

enter image description here

Emma
  • 27,428
  • 11
  • 44
  • 69