在字符串中搜索重复的连续字符,并用1或0替换每个字符串

时间:2017-11-11 09:01:47

标签: php regex preg-replace repeat non-repetitive

我有一个数组

$array = array("ab","aab","abb","abab","abaab","abbb");

我想搜索包含重复连续字符的元素,例如aababbabbb,并将其替换为1

相反,如果某个元素不包含任何重复的连续字符(例如ababab),则应将其替换为0

2 个答案:

答案 0 :(得分:1)

此方法使用array_map和preg_match基于重复字符串返回真/假匹配数组。键将匹配您的输入数组。

(.)找到任何字符并将其放入第一个捕获组,然后\1确保跟随它的完全匹配字符。

$array = array("ab","aab","abb","abab","abaab","abbb");
function StringHasRepetition( $string )
{
  return preg_match('/(.)\1/', $string);
}
$matches = array_map('StringHasRepetition',$array);
print_r( $matches );
// Array ( [0] => 0 [1] => 1 [2] => 1 [3] => 0 [4] => 1 [5] => 1 ) 

作为Lambda函数:

$array = array("ab","aab","abb","abab","abaab","abbb");
$matches = array_map( function( $string ){
  return preg_match('/(.)\1/', $string);
} ,$array);
print_r( $matches );
// Array ( [0] => 0 [1] => 1 [2] => 1 [3] => 0 [4] => 1 [5] => 1 )

答案 1 :(得分:1)

preg_replace()可以在一次调用中仅使用两个正则表达式模式操作整个数组。首先将没有连续重复字符的字符串转换为0。然后将所有非0值转换为1

代码:(See Demo Link for a more verbose breakdown of the method

$array=["ab","aab","abb","abab","abaab","abbb",'1','11','10','0','00100','1101','01'];
var_export(preg_replace(['/^(?:(.)(?!\1))*$/','/^(?!0$).*/'],[0,1],$array));

输出:

array (
  0 => '0',
  1 => '1',
  2 => '1',
  3 => '0',
  4 => '1',
  5 => '1',
  6 => '0',
  7 => '1',
  8 => '0',
  9 => '0',
  10 => '1',
  11 => '1',
  12 => '0',
)