I want to check if users are putting their phone number into a string.
Just need to check for 6 numbers (digits) in a row.
What is the best way to do this in PHP?
Example String:
blah blah553376and blah
I want to check if users are putting their phone number into a string.
Just need to check for 6 numbers (digits) in a row.
What is the best way to do this in PHP?
Example String:
blah blah553376and blah
Try this
$str = "blah blah553376and blah";
preg_match('!\d+!', $str, $matches);//You can use preg_match('!\d{6,}!', $str, $matches); also
if(isset($matches[0]) && is_numeric($matches[0]) && strlen(trim($matches[0])) >= 6){
echo $matches[0];
}
There are a few ways to approach this problem:
The regex solution, as pointed out by some others. I'm in no way a regex expert, but this seems to work:
$input_line="blah blah553376and blah";
$regex_line="/([a-z 0-9]*)([0-9]{6})([a-z 0-9]*)/i";
$output_array=Array();
preg_match($regex_line, $input_line, $output_array);
if($output_array[2])
{
echo("number is: ". $output_array[2]);
}
else
{
echo("number not found");
}
The exhaustive iteration method:
$input_line="blah blah553376and blah";
$output_string="";
for($i=0; $i<strlen($input_line);$i++)
{
$current_character = substr($input_line,$i,1);
if(is_numeric ( $current_character ))
{
$output_string .= $current_character;
}
else
{
//reset output
$output_string="";
}
if(strlen($output_string) >=6)
{
//bail out if requirements are met.
break;
}
}
if($output_string)
{
echo("number is: " . $output_string);
}
else
{
echo("number not found");
}
I'm sure there are other better ways, but above are just two simple ways off the top of my head to approach this.