0

文字列内のすべての文字が同一かどうか、つまり、文字列内に少なくとも 2 つの異なる文字があるかどうかを確認する方法は?


これは私の非動作の試みです:

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

単語が文字の単なる繰り返しであるかどうかを確認しようとしていると思います(つまり、1つの異なる文字しかありません)。

そのために単純な正規表現を使用できます。

$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

2 番目のパラメーターが 1 または 3 の文字列に使用count_charsします。文字列が 1 つの繰り返し文字で構成されている場合、次のようになります。

$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 に答える