View Full Version : PHP Regular expression [HTML]
imagined
September 12th, 2008, 02:18 PM
How can I create a ereg regular expression to match exactly the following:
[HTML]
i tried ^[HTML]$ but it doesnt seem to work.
Templarian
September 12th, 2008, 02:20 PM
you have to back slash [ and ] so:
/^\[html\]$/
^ and $ aren't really needed, but meh.
imagined
September 12th, 2008, 02:26 PM
If there is [HTML] on the string... shouldn't return a 1 or true?
if(ereg('/\[HTML\]/', $input))
imagined
September 12th, 2008, 02:50 PM
Ok I got it!
if(ereg("\[HTML\]", $input))
simplistik
September 12th, 2008, 04:50 PM
IMO you should use
eregi()
Voetsjoeba
September 12th, 2008, 05:13 PM
Imo you should use neither; the ereg functions are known to be slow and will in fact be removed out of the core in PHP6 in favor of the preg family, which will become the standard regular expression engine. Use Templarian's suggestion instead.
The reason why ^[html]$ didn't work is because [] are regex metacharacters that indicate a character class. You need to escape them to match a literal "[" and "]". Also, when using the preg family don't forget to enclose your regular expression in delimiters, like so:
preg_match('/^\[html\]$/', $subject);You can then specify modifiers that affect how the match is performed. For example, you'll probably want to use the "i" modifier (for case-insensitivity):
preg_match('/^\[html\]$/i', $subject);The delimiter can be any character you want; PHP will recognize it as long as it actually divides your regex from your modifiers (if any). Be aware that you will also have to escape the delimiter you've chosen inside your regular expression; otherwise, it would of course no longer be a delimiter. It's a good idea to pick a delimiter character that isn't used by your regular expression.
Another thing you'll want to look out for is to avoid using double quotes to specify a regular expression string, as PHP performs inline substitution in double-quoted strings. You really don't want to add another level of backslashing to something already as backslash-prone as regular expressions. Stick with single-quoted strings to specify your regular expressions.
eirche
September 12th, 2008, 07:39 PM
preg_match('/^\[html\]$/i', $subject) is a thousand times slower version of '[html]' == strtolower($subject).
use preg_match('/\[html\]/i', $subject)
match exactly the following: [html]
you dont need regex, just use strstr();
Powered by vBulletin® Version 4.1.10 Copyright © 2012 vBulletin Solutions, Inc. All rights reserved.