Can someone help me with a regular expression to include
A-z a-z 0-9 - _ (space) (dot) < > ( ) ~
and exclude other special symbols in ereg function of php 5.1.6?
I am getting too much confused with the escape character backslash and order of things i need to write if it is required. If not possible with ereg u can suggest me any similar function that works.
Thank you
Ereg version :
if (ereg('^[a-zA-Z0-9.<>()~ _-]+$', $subject)) {
# Successful match
}
Preg version : (after popular demand)
if (preg_match('/^[a-zA-Z0-9.<>()~ _-]+$/', $subject)) {
# Successful match
}
Something like this?
# ^[a-zA-Z0-9.<>()~ _-]+$
#
# Assert position at the beginning of the string «^»
# Match a single character present in the list below «[a-zA-Z0-9.<>()~ _-]+»
# Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
# A character in the range between “a” and “z” «a-z»
# A character in the range between “A” and “Z” «A-Z»
# A character in the range between “0” and “9” «0-9»
# One of the characters “.<>()~ ” «.<>()~ »
# The character “_” «_»
# The character “-” «-»
# Assert position at the end of the string (or before the line break at the end of the string, if any) «$»
This should do the trick:
[A-Za-z0-9 _.()~<>-]+
Here, match all the characters you want (the list inside []
). The +
at the end means 'match one or more of the characters in the set'.
To match a dash (-
), it must come last in the character list otherwise you end up with badly formed regex due to -
also denoting ranges of characters, like A-Z
for example.
Concerning your confusion over the escaping of characters, you don't actually need to do it as FailedDev pointed out, providing your characters are inside a character class: []
.
Finally, ereg_*()
is deprecated. Instead, use the preg_*()
functions.