oracle259 Posted July 10, 2006 Share Posted July 10, 2006 Hi I need to know to what extent can we use variable with regex e.g.is it possible to do this:$var1 = "abc.gov.jm";$var2 = "defg.gov.au";/^(?=.*?[a-zA-Z])(?:[a-zA-Z][0-9\-\.\_]?)+@(?:$var1|$var2)$/or if not what is the best way of achieving the same thing Quote Link to comment Share on other sites More sharing options...
shoz Posted July 11, 2006 Share Posted July 11, 2006 [quote=oracle259]HiI need to know to what extent can we use variable with regex e.g.is it possible to do this:$var1 = "abc.gov.jm";$var2 = "defg.gov.au";/^(?=.*?[a-zA-Z])(?:[a-zA-Z][0-9\-\.\_]?)+@(?:$var1|$var2)$/or if not what is the best way of achieving the same thing[/quote]Remember that the regex is a string, and you can create that string just as you would any other string in PHP.[code]$var = 'l';$regex = "/^$var\$/";//or$regex = '/^'.$var.'$/';//or$regex = "/^{$var}\$"/;[/code]The regex would be '/^l$/'. Although the "$" symbol at the end of the regex doesn't need to be escaped in this example, I think it's good practice to escape it when it's inside double quotes to be clear.It should also be considered good practice to surround any var that's "touching" other characters with "{}". Again, although not necessary in every situation is required in some for clarity.http://www.php.net/manual/en/language.types.string.php Quote Link to comment Share on other sites More sharing options...
effigy Posted July 11, 2006 Share Posted July 11, 2006 Follow the same interpolation rules as PHP, just be aware that you may need to pass your variable through preg_quote first. The periods in your example "abc.gov.jm" are not literal periods in regex. Quote Link to comment Share on other sites More sharing options...
shoz Posted July 11, 2006 Share Posted July 11, 2006 [quote=effigy]pass your variable through preg_quote first[/quote]Agreed. I'd say that's the more important thing to remember. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.