Home >Backend Development >PHP Tutorial >Replace any consecutive characters in a string with a corresponding character_PHP Tutorial
//1, replace any space in the string with a
$str1 = A B B C ;
echo
echo 1:;
echo preg_replace ("/s+/", , $str1);
echo
//2, replace any continuous character M in the string with an M
echo 2: ;
$str1 = AMMMBMMMMCMM ;
echo preg_replace ("/M+/", M, $str1) .
;
//3, replace any consecutive characters in the string Replace with a corresponding character
echo 3:
;
$str1 = ACCCB CCCCCGGG OOO YYYFFFXXXZZZZZ;
echo $str1 .
;
$str2 = ;
$ i = 0;
for ($i=0; $i
$str2 = $str2 . $str1{$i};
$ j = 1;
while ($str1{$i}==$str1{$i + $j})
$j++;
$i = $i + $j - 1;
}
echo $str2 .
;
//4, replace any consecutive characters in the string with a corresponding character
echo 4:
;
$str1 = ACCCB CCCCCGGG OOO YYYFFFXXXZZZZZ;
echo $str1 .
;
$len = strlen($str1);
$str2 = $str1[0];
$ch = $str2;
for($i=1; $i<$len; $i++){
$ch2=$str1[$i];
if($ch!=$ch2){
$ str2.=$ch2;
$ch=$ch2;
}
}
echo $str2 . "
";
//5, put the string in Replace any consecutive characters with a corresponding character
echo 5:
;
$str1 = ACCCB CCCCCGGG OOO YYYFFFXXXZZZZZ;
echo preg_replace("/(.)1+/", "[url =file://1]1[/url]", $str1) .
;
?>