0

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


这是我的非工作尝试:

<?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);
?>
4

3 回答 3

9

我认为您正在尝试查看一个单词是否只是一个字符的重复(即它只有一个不同的字符)。

您可以为此使用简单的正则表达式:

$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)

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

于 2013-06-18T16:31:51.633 回答
3

用于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
于 2013-06-18T16:31:17.930 回答
0

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

<?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

于 2013-06-18T16:33:07.677 回答