dongzhang2150 2014-11-20 08:44
浏览 24
已采纳

preg_replace在字符串中的相同单词

String: this is text :wall: :wall: :wall: :wall: more text

Output should be: this is text :wall: more text

Task: Reduce the word :wall: to only 1.

I tried these both ideas, but didn't work:

$post_message = preg_replace("/([\:wall:])+/", "\\1", $post_message);

$post_message = preg_replace('/:wall:/', '', $post_message, 1);
  • 写回答

4条回答 默认 最新

  • dongpo4197 2014-11-20 08:46
    关注

    Use the below regex in preg_replace function.

    Regex:

    (:wall:)(?:\s+:wall:)+
    

    OR

    (:wall:)(?:\s+\1)+
    

    Replacement string:

    $1
    

    DEMO

    Code:

    <?php
    $str = "this is text :wall: :wall: :wall: :wall: more text";
    echo preg_replace('~(:wall:)(?:\s+\1)+~', '$1', $str);
    ?>
    

    Output:

    this is text :wall: more text
    

    (:wall:) Captures the text :wall: into a group. This could be referred by group index 1. So this (?:\s+\1)+ matches the folowing one or more space + :wall: strings. Replacing the match with the chars inside group index 1 will remove all the duplicate :wall: strings.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度