我正在写一些代码,需要在字符串中搜索某些类型的符号。例如,如果我在字符串中搜索"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!
有人能帮帮忙吗?
发布于 2010-11-13 23:14:24
嗯,我可以建议用不同的方式来做吗?
function symbolsInRow($string, $limit = 5) {
$regex = '/(.)\1{'.($limit - 1).',}/us';
return 0 == preg_match($regex, $string);
}因此,基本上它只是查看连续(或更多)重复$limit次数的任何字符。如果找到,则返回false。否则它将返回true...
发布于 2010-11-13 23:20:00
您可以使用一个简单的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个相同的字符)
https://stackoverflow.com/questions/4172799
复制相似问题