我有一个字符串显示每个帖子,然后在帖子的末尾显示<hr>
元素。但我知道如果你删除它显示的帖子会留下<hr>
元素,所以我需要一个脚本来检测是否有多个<hr>
元素并将其缩小以便它只会在每个帖子下面留下一个。
是否有可能做到???
这就是我的样子:
post text post text post text post text post text
<hr>
post text post text post text post text post text post text
<hr>
<hr>
<hr>
<hr>
<hr>
<hr>
<hr>
<hr>
post text post text post text
<hr>
<hr>
post text post text post text post text
<hr>
我需要它像:
post text post text post text post text post text
<hr>
post text post text post text post text post text post text
<hr>
post text post text post text
<hr>
post text post text post text post text
答案 0 :(得分:2)
测试这个正则表达式:
$str = preg_replace('/(<hr>[\n\r\s]{0,}<hr>[\n\r\s]{0,}){1,}/', '<hr>', $str);
echo $str;
请参阅此实时运行代码:https://eval.in/521981
答案 1 :(得分:1)
<hr>
<hr>
preg_replace()
PHP:
<?php
$content = <<<STR
post text post text post text post text post textA
<hr>
post text post text post text post text post text post textB
<hr>
<hr>
<hr>
<hr>
<hr>
<hr>
<hr>
<hr>
post text post text post textC
<hr>
<hr>
post text post text post text post textD
STR;
function remove_duplicate_hr_tags($string)
{
$lines = explode('<hr>', $string);
$trimmedArray = array_map('trim', $lines);
$emptyRemovedArray = array_filter($trimmedArray);
$content = implode("\n<hr>\n", $emptyRemovedArray);
return $content;
}
echo remove_duplicate_hr_tags($content);
输出
post text post text post text post text post textA
<hr>
post text post text post text post text post text post textB
<hr>
post text post text post textC
<hr>
post text post text post text post textD
答案 2 :(得分:0)
可能会更有帮助。
我的建议是将它们分组为div。
<div class="container">
<p>post 1 text</p>
<hr>
</div>
<div class="container">
<p>post 2 text</p>
<hr>
</div>