【问题标题】:php / regex convert multiple paragraphs to one paragraph with line breaksphp / regex 将多个段落转换为一个带有换行符的段落
【发布时间】:2020-10-17 13:26:01
【问题描述】:

我想像这样转换一个字符串

<p>one</p>
<p>two</p>
<p>three</p>

到这里

<p>one<br>two<br>three</p>

(如果只有一个段落标签则保持不变)

所以我知道正则表达式基本上只需要用&lt;br&gt; 替换每个&lt;/p&gt;&lt;p&gt; 对,我可以将str_replace() &lt;/p&gt;&lt;p&gt; 替换为&lt;br&gt; 但可能会有换行符或结束之间的空格并打开 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)

干杯! :)

【问题讨论】:

  • 所以你只需要将&lt;/p&gt;\s*&lt;p&gt;替换为&lt;br&gt;?
  • $pattern = '~&lt;/p&gt;[^/]*&lt;p&gt;~'; 似乎做你想做的事。

标签: php regex wordpress string text


【解决方案1】:

使用

<?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);

proof

结果:

<p>one<br>two<br>three</p>
<p>one<br>two<br>three</p>

【讨论】:

  • 啊\s*它!现在似乎很明显,我想多了,谢谢! ?
猜你喜欢
  • 1970-01-01
  • 2013-03-03
  • 2017-09-27
  • 1970-01-01
  • 2021-11-09
  • 1970-01-01
  • 2011-03-09
  • 2015-06-30
  • 2013-02-07
相关资源
最近更新 更多