Reputation: 300
Say I have an integer 88123401
, and I want to determine whether it includes a sequence of numbers like 1234, 23456, 456789, or the like of any length and from any beginning of numbers.. Is this possible at all in PHP, and if so, how would one go about finding out?
Upvotes: 4
Views: 2029
Reputation: 13303
This might help you:
$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)));
This lists all the matches that are sequential in an array. We can process further based on the results.
Result:
Array
(
[0] => 1234
[1] => 01
)
Upvotes: 0
Reputation: 6253
Some function with a for so you go through all the string comparing each character with its predecessor.
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
Upvotes: 6
Reputation: 402
use a loop and use the answer of @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";
}
}
keeping it easy and straight forward.
Upvotes: 2
Reputation: 7491
Treat the number as a string and search with strpos()
.
Example:
$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";
}
Source: http://php.net/manual/en/function.strpos.php
Upvotes: 0