| 
	
 | 
 Posted by Toby A Inkster on 04/30/07 09:18 
M Kinnear wrote: 
 
> I want to check a string only contains a-z 0-9 ( ) . and # 
>  
> I've used 
>  
> ereg("^[a-zA-z0-9().#]*)$"),$instr) 
 
Firstly, it looks to me like a couple of extra brackets slipped into the 
code you posted, as I don't think the above would parse at all. I'm 
assuming what you're actually using is: 
 
	ereg("^[a-zA-z0-9().#]*$", $instr) 
 
Firstly, use preg_match. It runs faster that ereg; and ereg is being 
phased out in newer versions of PHP. This gives you: 
 
	preg_match("/^[a-zA-z0-9().#]*$/", $instr) 
 
Now, the dot (.) in regular expressions has a special meaning. It means 
"absolutely any character you want". This means that you are allowing 
absolutely any character at all -- that is, your regular expression is 
doing nothing. The dot needs to be escaped with a backslash: 
 
	preg_match("/^[a-zA-z0-9()\.#]*$/", $instr) 
 
Also, parentheses (these) have a special meaning within regular 
expressions, marking out subexpressions. IIRC, this shouldn't be a problem 
in your case because that special meaning disappears within square 
brackets. However, it doesn't hurt to escape them, and it looks a bit 
clearer to people just glancing at the expression: 
 
	preg_match("/^[a-zA-z0-9\(\)\.#]*$/", $instr) 
 
Now try it. 
 
> Second q: is there clarification on whether characters need to be 
> escaped when part of a regex statement? i.e., should it be [$] or [\$] - 
> some websites/posts state they should be escaped, others say they 
> shouldn't 
 
Generally it never hurts to escape, so when something could go either way, 
err on the side of escaping things. Note that there are two levels of 
escapes coming into play here -- firstly as you're using "double quotes" 
you need to escape against PHP's built in string-parsing. Secondly, you 
need to escape against special meanings of characters in regular 
expressions. 
 
To make things simpler, it is usually preferable to use 'single quotes', 
so that you only have to worry about one set of escaping. 
 
	preg_match('/^[a-zA-z0-9\(\)\.#]*$/', $instr) 
 
--  
Toby A Inkster BSc (Hons) ARCS 
http://tobyinkster.co.uk/ 
Geek of ~ HTML/SQL/Perl/PHP/Python*/Apache/Linux 
 
* = I'm getting there!
 
  
Navigation:
[Reply to this message] 
 |