Jump to content

Variables and Regex


oracle259

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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.