user2335065
user2335065

Reputation: 2547

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!

Upvotes: 1

Views: 65

Answers (3)

Emma
Emma

Reputation: 27723

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

Upvotes: 0

jspcal
jspcal

Reputation: 51894

Perhaps try

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

Upvotes: 2

user2450639
user2450639

Reputation: 196

Maybe use something like this:

str_replace(".","</p>.<p>", $myText);

Upvotes: 0

Related Questions