I’m trying to find the easiest validation regular expression (PCRE) for use in method preg_match() in PHP. I want to keep it as easy as possible and avoid repetition if possible.
My matching criteria in words is:
-
Allow one or more characters (this implies string should be 1 characters and up in total) from the following list:
a-zA-Z0-9 +&- - Do not allow space in beginning or end
My regular expression knowledge might be lacking but what I come up with without the second space criterion is:
/^[a-zA-Z0-9 +&-]+$/
To not match space I’m thinking about something like
/^[^ ]+[a-zA-Z0-9 +&-]+[^ ]+$/
but this actual piece would need 3+ characters.
If I do
/^[^ ]*[a-zA-Z0-9 +&-]+[^ ]*$/
it will not work at all times either, I suppose it has to do with the “greediness” of the middle part, but I’ve really tried to research how to get it right without succeeding.
Thankful for any kind of advice or pointer in the right direction!
You want to wrap both
[^ ]conditions into assertions. Lefthand(?=)and(?<=)at the end.I think it’s sufficient if you test just for one non-space character on each end. Then it’s already ensured the content begins with a letter or another allowed character.
See http://www.regular-expressions.info/lookaround.html for a nice explanation.