In a form I have an ID field, which needs to check that the first letter is "P" and is 5 characters long.
I have looked into preg_match but I have no idea how to get it working. It seems to be able to check how many "P"s the would be and where they are, but how do I get that to check that only entries starting with "P" are passed.
Big time PHP noobie so doesn't need to be anything awesome. I really don't get PHP. :(
To check if a string starts with P and is 5 characters long, using preg_match, as you asked for, I would write (lazily)
<?php
if (preg_match('/^P....$/', $your_ID_variable) === 1) {
print 'your ID is starting with a P and is 5 characters long.';
}
?>
But as posted from others, there are other ways to do it, like:
<?php
if ((strlen($your_ID_variable) == 5)
&& (strpos($your_ID_variable, 'P') === 0)) {
print 'your ID is starting with a P and is 5 characters long.';
}
?>
Here are some sources you could have found:
You can simply use :
<?php
$string = 'abcdef';
$first_character = $string[0];
if($first_character!="P"){
//Do something
}
//Check length
if(strlen($string)<6){
//Do something
}
?>
Go through : http://php.net/manual/en/function.substr.php for more info.
if (strpos($string, 'P') === 0 && strlen($string) == 5) {
// do something...
}
You could simplify it into two tasks without regular expressions:
$starts_with_p = (strpos($id_string, 'P') === 0);
$is_five_chars = (strlen($id_string) == 5);
$valid_id = ($starts_with_p && $is_five_chars);
You can simply use this regex to check:
$name = "poiuy";
if(preg_match("%^p.{4}$%i", $name)){
//do something
}
lets say $id
is that variable in which you have id then you can get first character like $id[0]
this is faster than substr
and for length you can do strlen($id)
How about this.
$string="Pabcd";
if(preg_match("/^P[A-Za-z]{4}/", $string))
{
echo "string matched";
}
else
{
echo "string not matched";
}
please correct me if iam wrong.