PHP-从字符串中删除重复的元素(<;hr>;)
我有一个显示每篇文章的字符串,然后在文章末尾有一个PHP-从字符串中删除重复的元素(<;hr>;),php,function,post,Php,Function,Post,我有一个显示每篇文章的字符串,然后在文章末尾有一个元素。但是我有这样一个脚本,如果你删除一篇文章,它会将元素保留在那里,因此我需要一个脚本来检测是否有多个元素,并缩小它的范围,以便在每篇文章下面只保留一个元素 有可能吗 以下是它在我看来的样子: post text post text post text post text post text <hr> post text post text post text post text post text post text <
元素。但是我有这样一个脚本,如果你删除一篇文章,它会将
元素保留在那里,因此我需要一个脚本来检测是否有多个
元素,并缩小它的范围,以便在每篇文章下面只保留一个元素
有可能吗
以下是它在我看来的样子:
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 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
post text post text post text
后置文字后置文字后置文字后置文字后置文字后置文字后置文字
后置文字后置文字后置文字
后置文字后置文字后置文字后置文字后置文字
测试此正则表达式:
$str = preg_replace('/(<hr>[\n\r\s]{0,}<hr>[\n\r\s]{0,}){1,}/', '<hr>', $str);
echo $str;
$str=preg\u replace('/(
[\n\r\s]{0,}
[\n\r\s]{0,}){1,}/','
',$str);
echo$str;
查看此实时运行代码:如果您提供代码,可能会更有帮助 我的建议是把他们分组
<div class="container">
<p>post 1 text</p>
<hr>
</div>
<div class="container">
<p>post 2 text</p>
<hr>
</div>
Post1文本
Post2文本
- 我在这里使用爆炸
- 然后过滤掉空元素
- 然后用
- 可能比
preg\u replace()更贵
一些您迄今为止尝试过的PHP代码会很有帮助-不仅可以查看问题所在,还可以理解您的问题:如何“删除”帖子?你如何渲染它们?当你删除文章时,删除< <代码> HR > <代码>?如果回答了你的问题,请考虑接受答案!更昂贵但更直观(比我的答案)!RegExp一行程序功能强大,但总是有点复杂:)而且有很多方法可以实现。。。
<?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