dongxin5054 2016-02-19 20:16
浏览 155
已采纳

PHP - 从字符串中删除重复的元素(<hr>)

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 
  • 写回答

3条回答 默认 最新

  • dongping1012 2016-02-19 20:50
    关注
    • 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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号