PHP - 从字符串中删除重复的元素(
)
I have a string that shows each post then a <hr>
element at the end of a post. But I have it so if you delete a post it shows leaves the <hr>
element there so I need a script that will detect if there is more than one <hr>
element and narrow it down so that it will only be left with one below each post.
Is there any chance that it is possible to do???
here is what it looks like to me:
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>
And I need it to be like:
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
我有一个字符串,显示每个帖子,然后是 是否有可能做到??? p>
这就是我的样子: p>
我需要它 喜欢: p>
&lt; hr&gt; code>元素 一篇文章的结尾。 但我知道如果你删除它显示的帖子会留下
&lt; hr&gt; code>元素,所以我需要一个脚本来检测是否有多个
&lt; hr&gt; code> element并缩小它以便它只留下每个帖子下面的一个。 p>
post text text post text post text text post text text
&lt; hr&gt;
post text post post text post text 发布文本发布文本发布文本
&lt; hr&gt;
&lt; hr&gt;
&lt; hr&gt;
&lt; hr&gt;
&lt; hr&gt;
&lt; hr&gt;
&lt; hr&gt;
&lt; hr&gt;
post text post text post text n&lt; hr&gt;
&lt; hr&gt;
post text post text text post text post text
&lt; hr&gt;
code> pre>
发布文本发布文本发布文本发布文本发布文本
&lt; hr&gt;
post text post text text post text post text text post text text
&lt; hr&gt; \ npost text post text text post text
&lt; hr&gt;
post text post text text post text te xt
code> pre>
div>
- i'm using an explode
<hr>
here - then filtering out the empty elements
- and then simply re-imploding with
<hr>
- probably more expensive then a
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("
<hr>
", $emptyRemovedArray);
return $content;
}
echo remove_duplicate_hr_tags($content);
Output
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
Test this regex:
$str = preg_replace('/(<hr>[
\s]{0,}<hr>[
\s]{0,}){1,}/', '<hr>', $str);
echo $str;
See this live running code : https://eval.in/521981
could have been more helpful if you provide code.
my suggestion would be group them in div .
<div class="container">
<p>post 1 text</p>
<hr>
</div>
<div class="container">
<p>post 2 text</p>
<hr>
</div>