Products
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:
I only want to keep the 1st occurrence and remove all others. What will find and remove exact duplicates?
图片转代码服务由CSDN问答提供
感谢您的意见,我们尽快改进~
功能建议我正在寻找能找到精确重复模式的正则表达式(区分大小写)。 例如,名称字符串中的中间名首字母。 示例:</ p>
</ ul>
我只想保留第一次出现并删除所有其他出现。 什么会找到并删除完全重复的内容?</ p>
</ div>
You can use this in php
:
$repl = preg_replace(\'/\\b([a-zA-Z]\\W+)\\1+/u\', \'$1\', $str);
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, unset
ting 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中可以使用内置函数array_unique()来直接删除重复元素,也可以使用array_flip()函数来间接删除重复元素。
array_unique()函数
array_unique()函数可以移除数组中的重复的值,并返回结果数组;当几个数组元素的值相等时,只保留第一个元素,其他的元素被删除。
代码示例:
Demand feedback