【问题标题】:Wrap text with <p> until the first <p> appears用 <p> 换行直到第一个 <p> 出现
【发布时间】:2019-06-06 17:27:15
【问题描述】:
如何从字符串的开头换行直到第一个 <p> 出现?例如,如果字符串是
this is some <b>text</b><p>Beginning of a paragraph</p>
我想要
<p>this is some <b>text</b></p><p>Beginning of a paragraph</p>
有什么方法可以做到这一点?谢谢!
【问题讨论】:
标签:
php
regex
dom
preg-replace
html-manipulation
【解决方案1】:
不妨试试
$str = '<p>' . preg_replace('#<p>#', '</p>\0', $str, 1);
【解决方案2】:
也许使用这样的东西:
str_replace(".","</p>.<p>", $myText);
【解决方案3】:
如果我们的输入和问题中的一样简单,我们将从一个简单的表达式和一个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;
输出
<p>this is some <b>text</b><\/p><p>Beginning of a paragraph</p>
正则表达式电路
jex.im 可视化正则表达式: