其他教程

其他教程

Products

当前位置:首页 > 其他教程 >

使用PHP正则表达式搜索精确的重复序列(并删除所有重复序列)

GG网络技术分享 2025-03-18 16:15 0


问题描述:

I\'m looking for a regex that will find an exact repeating pattern (case-sensitive). For instance, middle initials in a name string. Examples:

  • Jim G G Bob is a match on \" G \" x 2
  • Jim G. G. Bob is a match on \" G. \" x 2
  • Tom H H H Ford is a match on \" H \" x 3 and so on ...
  • Sarah H Howard is NOT a match because we have \"h \", \"H \", and \" H\" (which are all unique)

I only want to keep the 1st occurrence and remove all others. What will find and remove exact duplicates?

图片转代码服务由CSDN问答提供

感谢您的意见,我们尽快改进~

功能建议

我正在寻找能找到精确重复模式的正则表达式(区分大小写)。 例如,名称字符串中的中间名首字母。 示例:</ p>

  • Jim GG Bob匹配“G”x​​ 2 </ li>

  • Jim GG Bob与“G”匹配 x 2 </ li>

  • Tom HHH Ford对阵“H”x 3等等...... </ li>

  • Sarah H Howard不是一场比赛,因为我们有“h” “,”“H”和“H”(都是唯一的)</ li>

    </ ul>

    我只想保留第一次出现并删除所有其他出现。 什么会找到并删除完全重复的内容?</ p>

    </ div>

    网友观点:

    You can use this in php:

    $repl = preg_replace(\'/\\b([a-zA-Z]\\W+)\\1+/u\', \'$1\', $str);

    RegEx Demo

    RegEx Breakup:

    \\b           # word boundary

    ( # capturing group #1 start

    pL # match a single unicode letter

    \\W+ # match 1 or more non-word character

    ) # capturing group #1 start

    \\1+ # match 1 or more of captured group #1 to match *repeats*

    A non-regex way to solve this general problem: explode on space and loop over the resulting array, unsetting each key where the value is the same as the previous, then implode to form the sequential-duplicate-free string.

    $words = explode(\' \', $string);

    $previous = null;

    foreach ($words as $key => $value) {

    if ($value == $previous) unset($words[$key]);

    $previous = $value;

    }

    $string = implode(\' \', $words);

    如何使用PHP删除数组中的重复元素?

    在PHP中可以使用内置函数array_unique()来直接删除重复元素,也可以使用array_flip()函数来间接删除重复元素。

    array_unique()函数

    array_unique()函数可以移除数组中的重复的值,并返回结果数组;当几个数组元素的值相等时,只保留第一个元素,其他的元素被删除。

    代码示例:

标签:

提交需求或反馈

Demand feedback