What is the best way to check a certain input in php and proceed if it meets the required format?
Question
I got lost in a using strpos() and ltrim()'s. Would anyone be able to help me out with my problem? I'd want the page to only accept inputs that start with "A" or "B" then is immediately followed by an integer. Like the following:
A1 = accepted
B1 = accepted
AB = rejected
1A = rejected
1 = rejected
B123 = accepted
I am using $_GET
and the URL is somehow like page.php?id=
The numbers actually come from an auto-increment primary key in MySQL so lengths will vary as entries are added.
Solution
php > $pattern="/^[A|B]\d+$/";
php > echo preg_match($pattern,"A1",$matches); print_r($matches);
1Array
(
[0] => A1
)
php > echo preg_match($pattern,"B1",$matches); print_r($matches);
1Array
(
[0] => B1
)
php > echo preg_match($pattern,"1A",$matches); print_r($matches);
0Array
(
)
php >
OTHER TIPS
You should always try to avoid regexp. It is bad style because it is hard to read and difficult to debug. It is not so much shorter anyway:
preg_match("/^[A|B]\d+$/", $i, $m); if (count($m) > 0) {}
if ($i[0] == 'A' || $i[0] == 'B') && is_numeric(substr($i, 1)) {}
Full code:
if (isset($_GET['id']))
{
$id = $_GET['id'];
// A or B and the rest a number
if (($id[0] == 'A' || $id[0] == 'B') && is_numeric(substr($id, 1)))
{
// accepted
}
}
$id = isset($_GET['id']) ? ltrim($_GET['id']) : null;
if( $id && ($id[0]=='A'||$id[0]=='B') && is_numeric(substr($id,1)) ){
echo 'accepted';
}else{
echo 'rejected';
}
if (preg_match('/^([AB][0-9])/', $yourstring) > 0)
{
// valid input
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow