如何检查字符串中的所有字符是否相同


How to check if all characters in a string are the same?

如何检查字符串中的所有字符是否相同,或者换句话说,字符串中是否至少有两个不同的字符?


这是我不工作的尝试:

<?php
$isSame = False;
$word = '1111';//in any language
$word_arr = array();
for ($i=0;$i<strlen($word);$i++) {
    $word_arr[] = $word[$i];
    if($word_arr[$i] == $word[$i]) $isSame = True;
}
var_dump($isSame);
?>

我想你是想看看一个单词是否只是一个字符的重复(即。它只有一个不同的字符)

你可以使用一个简单的正则表达式:

$word = '11111';
if (preg_match('/^(.)'1*$/u', $word)) {
    echo "Warning: $word has only one different character";
}

正则表达式解释:

^   => start of line (to be sure that the regex does not match
       just an internal substring)
(.) => get the first character of the string in backreference '1
'1* => next characters should be a repetition of the first
       character (the captured '1)
$   => end of line (see start of line annotation)

所以,简而言之,确保字符串只有第一个字符的重复,而没有其他字符。

使用count_chars作为第二个参数为1或3的字符串。如果您的字符串包含一个重复字符,例如:

$word = '1111';
// first check with parameter = 1
$res = count_chars($word, 1);
var_dump($res);
// $res will be one element array, you can check it by count/sizeof
// second check with parameter = 3
$res = count_chars($word, 3);
var_dump($res);
// $res will be string which consists of 1 character, you can check it by strlen

似乎要检查所有字符是否相同

<?php
$isSame = True;
$word = '1111';
$first=$word[0];
for ($i=1;$i<strlen($word);$i++) {
    if($word[$i]!=$first) $isSame = False;
}
var_dump($isSame);
?>

PHPFiddle