[英]php / regex convert multiple paragraphs to one paragraph with line breaks
我想转换这样的字符串
<p>one</p>
<p>two</p>
<p>three</p>
对此
<p>one<br>two<br>three</p>
(如果只有一个段落标签,则保持不变)
所以我知道的正则表达式将基本上只需要替换每个</p><p>
对有<br>
,我可能只是str_replace()函数</p><p>
有<br>
,但会有可能换行符或关闭和打开 p 标签之间的空格。
所以使用正则表达式,就像这样。 但这会去掉“两个”(因为它位于结尾和开头 p 标记之间)。 它似乎也打破了新的行?
<?php
$string = '<p>one</p><p>two</p><p>three</p>';
$string2 = '<p>one</p>
<p>two</p>
<p>three</p>';
$pattern = '~</p>.*<p>~';
$replacement = '<br>';
echo preg_replace($pattern, $replacement, $string);
echo preg_replace($pattern, $replacement, $string2);
// Outputs "<p>one<br>three</p><p>one</p>" and "<p>one</p>
// <p>two</p>
// <p>three</p>"
有谁知道如何修复该正则表达式或知道更好的方法?
(我正在使用 Wordpress 以防有一些辅助功能)
干杯! :)
用
<?php
$string = '<p>one</p><p>two</p><p>three</p>';
$string2 = '<p>one</p>
<p>two</p>
<p>three</p>';
$pattern = '~</p>\s*<p>~u';
$replacement = '<br>';
echo preg_replace($pattern, $replacement, $string) . PHP_EOL. preg_replace($pattern, $replacement, $string2);
见证明。
结果:
<p>one<br>two<br>three</p>
<p>one<br>two<br>three</p>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.