Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check if a String contains the same letter twice consecutively in php?

Tags:

html

regex

php

I don't see why my code doesn't work, any suggestions?

$pattern_c_sap='/\.\-/';
$local='.................';
$local_array = explode( '', $local );

for($i=0; $i<=$local_length; $i++){
if(preg_match($pattern_c_sap , $local_array[$i]) && preg_match($pattern_c_sap , $local_array[$i+1])) {
    return false;
}
}

I had the following errors: The regex should be

[/\.\-/]

and I should have used str_split instead of explode when splitting for each letter.

like image 496
Andreas Hartmann Avatar asked Sep 17 '13 12:09

Andreas Hartmann


People also ask

How do you check if a character is repeated in a string PHP?

<? php $string = "aabbbccddd"; $array=array($array); foreach (count_chars($string, 1) as $i => $val) { $count=chr($i); $array[]= $val. ",". $count; } print_r($array); ?>

How do I check if a string contains the same character more than once?

You can use grep . The regexp \(. \). *\1 matches any single character, followed by anything, followed by the same first character.

How do you print duplicate characters from a string PHP?

php $string = "learnetutorials.com"; $string = strtolower($string); $size = strlen($string); echo "The entered string is : $string \n"; echo "The duplicate characters in the string are: \n"; for ($i = 0; $i < $size; $i++) { $count = 1; for ($j = $i + 1; $j < $size; $j++) { if ($string[$i] == $string[$j] && $string[$i] ...


1 Answers

You can use a preg_match like below:

if(preg_match('/(.)\1/', $local, $match){
    echo "contains consecutive characters";
}

(.) captures a character.

\1 refers to the captured character.

So, if you have AA, the (.) captures A and \1 will mean A. So the regex will be checking for AA.

like image 172
Jerry Avatar answered Oct 11 '22 01:10

Jerry