I'm trying to use regex to validate input from the user, I'm wanting to allow any letter in the alphabet, numbers, spaces and the following symbols:
! £ $ % & * ( ) _ + [ ] : ; @ ~ # < > ? , . -
I've never been that good with regex as it confuses the hell out of me. This is the best I've got but it's not working properly because if I put a ? in the field I receive the error.
<?php
$title = $_POST['title'];
if (!preg_match('/\/^[a-zA-Z0-9\s!£$%&*()_+[\]:;@~#<>?,.-]+$\//m', $title)) {
$error = "Photo name contains unsafe characters.";
$solution = "<a href=\"javascript:history.go(-1)\">Try again?</a>";
}
if ($error) { echo("$error");
?>
Why am I always getting these regex 开发者_Go百科things wrong, just when I think I'm beginning to understand, I soon realise I'm really not! :P
If anyone could help me out and maybe explain why my example doesn't work so I can learn from my mistakes that would be very appreciated, thank you!
You have some extra /
before the ^ and after the $, this one should work:
preg_match('/^[a-zA-Z0-9\s!£$%&*()_+[\]:;@~#<>?,.-]+$/m', $title)
Also the m
modifier would cause $
to match the end of the line, and allow someone to add any character after the first line, so you should remove it.
精彩评论