Reputation: 7194
I need to identify that a string starts and ends with a numeric value and 7 digit long.
Let- 1000453
or 0984567
. Those two string is start with a numeric value and end with a numeric value.If any string start with any character let say - a234567
than it show fail.
pls kindly suggest in PHP.
Thanks in advance
Upvotes: 0
Views: 303
Reputation: 195
In addition to the solutions using regular expressions above, the following should also do the job. I haven't tested it though!
$result = TRUE;
if (strlen($string) == 7)
{
$string_arr = str_split($string);
if (!(ctype_digit($string_arr[0]] && ctype_digit($string_arr[6])))
$result = FALSE;
}
else
$result = FALSE;
return $result;
Upvotes: 0
Reputation: 95582
is_numeric() is mildly risky. The string '1e5' might mean 10000 in scientific notation, but it might not.
Your problem calls for a regular expression.
/[0-9][0-9][0-9][0-9][0-9][0-9][0-9]/
or the simpler
/[0-9]{7}/
Upvotes: 0
Reputation: 4678
Try this
<?php
$string = "984f1a3";
if(strlen($string) <= 7){
if(!is_numeric(substr($string, 0, 1)) and !is_numeric(substr($string, strlen($string)-1, strlen($string)))) echo "FAIL";
else echo "Success";
}
else echo "FAIL";
Upvotes: 0
Reputation: 881463
You should be able to use a regex for this:
$count = preg_match ('/^[0-9].{5}[0-9]$/', $value)
That basically gives you every string that starts and ends with a digit with any five characters in-between. $count
is the number of matches found with non-zero meaning it matched.
If you want a different pattern, just adjust the regex. For example, seven characters, all numeric would be '/^[0-9]{7}$/'
.
Keep in mind I'm old-school and still use [0-9]
for digits since not all regex engines support the \d
notation, but PHP should be okay with that (such as '/^\d{7}$/'
).
Upvotes: 8
Reputation: 20878
Do you want only numbers?
Then this should work
if (preg_match("/^[0-9]{7}$/", $argv[1]))
{
echo "Ok";
}
If you also want to have other possible values in the string the regex of paxdiablo is right.
Upvotes: 1