Jump to content

Archived

This topic is now archived and is closed to further replies.

oracle259

Variables and Regex

Recommended Posts

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

Share this post


Link to post
Share on other sites
[quote=oracle259]
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]
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

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
[quote=effigy]
pass your variable through preg_quote first
[/quote]
Agreed. I'd say that's the more important thing to remember.

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.