View Full Version : '[' causing problems in php

06-14-2007, 05:12 AM
i keep getting errors from this line of code:
ereg("[url", $comment)this is the error: Warning: ereg() [function.ereg]: REG_EBRACK in /home/mobile/public_html/addcomment.php

however this works:
ereg("http", $comment)so i'm inclined to think it's the '[' that's causing the problems. any idea how i can fix this?


06-14-2007, 05:55 AM
[ like many other characters needs escaping when using in double quotes ", you can escape it or alternatively use single quotes ' i.e.:

ereg("[url", $comment)

06-14-2007, 06:07 AM
I've never used the ereg() function, but I regularly use the preg_match() function (which is almost the same), and the '[' character must be escaped, because it denotes the start of a character group.

I'm not entirely sure how you do that with ereg(), but with preg_match() you escape it with the '\' character.

I recommend you use the preg_match() function, as I believe that's faster and much more widely supported.

06-14-2007, 06:46 AM
You definately don't want to use ereg.

preg_match has a corresponding function for escaping special characters.

$delimiter = '/';
$pattern = $delimiter . preg_quote('[url', $delimiter) . $delimiter;
$result = preg_match($pattern, $comment, $matches);

However, if you're just searching for simple strings, its easier to use str_pos:

$position = strpos($comment, '[url');

Watch out for the difference between a FALSE and a 0 return value from strpos. Use === FALSE or is_int to compare the result of strpos to determine if the string was found.