Regular expression with a * in php
I want to use a basic regular exp开发者_高级运维ression to check whether a string contains only numbers and alphabet characters so I tried
preg_match('[a-zA-Z0-9]*', $address)
Which unfortunately returns an error:
Warning: preg_match() [function.preg-match]: Unknown modifier '*' in /bla/bla.php on line XX
It's a simple regex. Where am I getting it wrong?
The pattern should begin and end with a pattern delimiter. Different preg options, like case-insensitive search can be added after the delimiter. Usually slash (/) is used for delimiter, but can be any symbol (the delimiter should be escaped in the pattern):
preg_match('/[a-z0-9]*/i', $address);
This will check if the string has numbers or characters in it.
If you want to make sure that it has only numbers and characters, then use this:
preg_match('/^[a-z0-9]*$/i', $address);
You can use ctype_alnum
instead.
I use this to find all possible alphabetic characters from different languages as well:
preg_match('/^[\p{L}\p{M}0-9]+$/i', $address);
But if just English then:
preg_match('/^[a-z0-9]+$/i', $address);
use
preg_match('/^[a-zA-Z0-9]*$/', $address)
you forgot the slashes for the regex :
preg_match('/[a-zA-Z0-9]*/', $address)
http://www.ideone.com/G2TA3
精彩评论