简体   繁体   English

PHP用更少的字母数替换所有重复的字母

[英]PHP Replace any repeated letters with less number of letters

I would like to reduce a sequence of the same 5 repeating numbers or letters to a sequence of the same 2 repeating numbers or letters. 我想将相同的5个重复数字或字母的序列减少为相同的2个重复数字或字母的序列。

ie aaaaa => aa 即aaaaa => aa

Problem: 问题:

I am unsure on what parttern to put in the preg_replace() parameters. 我不确定要在preg_replace()参数中放置什么样式。

Example: 例:

preg_replace('/[a-zA-Z0-9]{5}/','/[a-zA-Z0-9]{2}/',$str);

Any Ideas about this ? 有任何想法吗? :) :)

You need to use a capture group and a backreference: 您需要使用捕获组和反向引用:

$str = preg_replace('~([a-zA-Z0-9])\1{4}~', '$1$1', $str);

or 要么

$str = preg_replace('~([a-zA-Z0-9])\1\K\1{3}~', '', $str);

details pattern 1: 细节模式1:

~                # pattern delimiter
(                # open the capture group 1
    [a-zA-Z0-9] 
)                # close the capture group 1
\1{4}            # backreference: repeat 4 times the content of the capture group 1
~

In the replacement string $1 refers to the content of the capture group 1. (as \\1 in the pattern) 在替换字符串$1引用捕获组1的内容。 (在模式中为\\1

The second pattern is not really different, it use only the \\K feature that removes all on the left from the match result. 第二种模式并没有什么不同,它仅使用\\K功能,将匹配结果左侧的所有内容都删除了。 With this trick, you don't need to put the two letters in the replacement string since they are preserved. 使用此技巧,由于保留了两个字母,因此无需将它们放在替换字符串中。 Only the last 3 letters are replaced. 仅替换最后3个字母。

Here's a way to do it with simple string functions and basic programming constructs: 这是使用简单的字符串函数和基本的编程结构来实现的一种方法:

$str="aaaaa 11111 bbbbb";
for($ascii=32;$ascii<=126;$ascii++) {
  $char=chr($ascii);
  $charcharcharcharchar=$char . $char . $char . $char . $char;
  $charchar=$char . $char;
  if(strpos($str, $charcharcharcharchar) !== FALSE) { $str=str_replace($charcharcharcharchar, $charchar, $str); }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM