Jump to content


Photo

Variables and Regex


  • Please log in to reply
3 replies to this topic

#1 oracle259

oracle259
  • Members
  • PipPipPip
  • Advanced Member
  • 119 posts

Posted 10 July 2006 - 10:20 PM

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

#2 shoz

shoz
  • Staff Alumni
  • Advanced Member
  • 600 posts

Posted 11 July 2006 - 02:25 AM

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

Remember that the regex is a string, and you can create that string just as you would any other string in PHP.
$var = 'l';
$regex = "/^$var\$/";

//or
$regex = '/^'.$var.'$/';

//or
$regex = "/^{$var}\$"/;
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/m...ypes.string.php

#3 effigy

effigy
  • Staff Alumni
  • Advanced Member
  • 3,600 posts
  • LocationIL

Posted 11 July 2006 - 02:28 AM

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.
Regexp | Unicode Article | Letter Database
/\A(e)?((1)?ff(?:(?:ig)?y)?|f(?:ig)?)\z/

#4 shoz

shoz
  • Staff Alumni
  • Advanced Member
  • 600 posts

Posted 11 July 2006 - 02:37 AM

pass your variable through preg_quote first

Agreed. I'd say that's the more important thing to remember.




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users