我正在编写一些代码,需要在字符串中搜索某些符号。我使用mb_strpos函数,它适用于字母符号,但如果我搜索问号,点等符号,则不会。例如,如果我在字符串中搜索“aaaaa”(或任何其他unicode字符)mb_strpos按预期工作,但如果我搜索“?????”它没有!
这是我的代码:
function symbols_in_row($string, $limit=5) {
//split string by characters and generate new array containing each character
$symbol = preg_split('//u', $string, -1, PREG_SPLIT_NO_EMPTY);
//remove duplicate symbols from array
$unique = array_unique($symbol);
//generate combination of symbols and search for them in string
for($x=0; $x<=count($unique); $x++) {
//generate combination of symbols
for($c=1; $c<=$limit; $c++) {
$combination .= $unique[$x];
}
//search for this combination of symbols in given string
$pos = mb_strpos($string, $combination);
if ($pos !== false) return false;
}
return true;
}
在第二种情况下总是返回true!
有人可以帮忙吗?
答案 0 :(得分:1)
好吧,我可以建议以不同的方式进行吗?
function symbolsInRow($string, $limit = 5) {
$regex = '/(.)\1{'.($limit - 1).',}/us';
return 0 == preg_match($regex, $string);
}
所以基本上它只是查看连续重复$limit
次的任何字符(或更多)。如果找到,则返回false
。否则返回true
...
答案 1 :(得分:1)
您可以使用简单的regExp执行此操作:
<pre>
<?php
$str="Lorem ipsum ?????? dolor sit amet xxxxx ? consectetuer faucibus.";
preg_match_all('@(.)\1{4,}@s',$str,$out);
print_r($out);
?>
</pre>
解释表达式:
(.)
匹配每个字符并创建对它的引用
\1
使用此引用
{4,}
引用必须发生4次或更多次(因此,使用此4个字符和引用本身,您将匹配5个相同的字符)