Jump to content

Variables and Regex


oracle259

Recommended Posts

[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
Link to comment
https://forums.phpfreaks.com/topic/14235-variables-and-regex/#findComment-55959
Share on other sites

Archived

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

×
×
  • Create New...

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.