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

Php 如何检查字符串中的所有字符是否相同?,php,Php,如何检查字符串中的所有字符是否相同,或者换句话说,字符串中是否至少有两个不同的字符 这是我的非工作尝试: <?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;

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

这是我的非工作尝试:

<?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);
?>
用于第二个参数为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

我想你是想看看一个单词是否只是一个字符的重复,也就是说,它只有一个不同的字符

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

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

因此,简而言之,请确保字符串只重复其第一个字符,而不重复其他字符。

看起来像是要检查所有字符是否相同

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

请确保您的代码是可读的,因为单词字符作为问题没有多大意义。请尽量多解释一下你想做什么。RTLM:你能更好地解释一下你想做什么吗?什么不起作用?你是真是假?该代码应该可以工作。我刚刚测试过。谢谢。这正是我想要的。这个正则表达式不支持一些语言,比如俄语或阿拉伯语@A如果字符串是UTF8编码的,请使用PCRE_UTF8模式修饰符。@您能在此处粘贴新代码吗?这里还有一个-简单、便宜、多字节安全:$IsName==str_replacemb_substr$word,-1,$word;