【问题标题】:Wrap text with <p> until the first <p> appears用 <p> 换行直到第一个 <p> 出现
【发布时间】:2019-06-06 17:27:15
【问题描述】:

如何从字符串的开头换行直到第一个 &lt;p&gt; 出现?例如,如果字符串是

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;
      

      Demo

      输出

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

      正则表达式电路

      jex.im 可视化正则表达式:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-08-14
        • 2014-12-18
        • 1970-01-01
        • 1970-01-01
        • 2016-09-06
        • 1970-01-01
        相关资源
        最近更新 更多