假设我有一个整数88123401
,我想确定它是否包含任意长度和任何数字开头的1234,23456,456789等数字序列。这是否可能在PHP中,如果是这样的话,怎么会发现?
答案 0 :(得分:4)
一些带有for的函数,所以你要经历所有字符串,将每个字符与其前一个字符进行比较。
function doesStringContainChain($str, $n_chained_expected)
{
$chained = 1;
for($i=1; $i<strlen($str); $i++)
{
if($str[$i] == ($str[$i-1] + 1))
{
$chained++;
if($chained >= $n_chained_expected)
return true;
}else{
$chained = 1;
}
}
return false;
}
doesStringContainChain("6245679",4); //true
doesStringContainChain("6245679",5); //false
答案 1 :(得分:2)
使用循环并使用@jtheman的答案
$mystring = '88123401';
$findme = array(123,2345,34567);
foreach ( $findme as $findspecificnum ) {
$pos = strpos($mystring, $findme);
if ($pos === false) {
echo "The sequence '$findme' was not found in the number '$mystring'";
} else {
echo "The sequence '$findme' was found in the number '$mystring'";
echo " and exists at position $pos";
}
}
保持简单直接。
答案 2 :(得分:0)
将数字视为字符串,并使用strpos()
进行搜索。
示例:
$mystring = '88123401';
$findme = '1234';
$pos = strpos($mystring, $findme);
if ($pos === false) {
echo "The sequence '$findme' was not found in the number '$mystring'";
} else {
echo "The sequence '$findme' was found in the number '$mystring'";
echo " and exists at position $pos";
}
答案 3 :(得分:0)
这可能会对您有所帮助:
$number = "88123401";
$splittedNumbers = str_split($number);
$continuous = false;
$matches[0] = '';
$i = 0;
do {
if ((int)(current($splittedNumbers) + 1) === (int)next($splittedNumbers)) {
if($continuous) {
$matches[$i] .= current($splittedNumbers);
}
else {
$matches[$i] .= prev($splittedNumbers) . next($splittedNumbers);
$continuous = true;
}
} else {
$continuous = false;
$matches[++$i] = '';
}
prev($splittedNumbers);
} while (!(next($splittedNumbers) === false));
print_r(array_values(array_filter($matches)));
列出了数组中连续的所有匹配项。我们可以根据结果进一步处理。
<强>结果:强>
Array
(
[0] => 1234
[1] => 01
)