...

View Full Version : Need a regular expression for this..



louislouis
01-29-2010, 01:43 PM
I really suck with regular expressions so wondering if any pro's can help me out.

Here's the string format I'm trying to match:

{$alphanumeric}

So it starts with {$ and ends with a } in between will be a random alphanumeric label.




<?php
$string = "{$alphanumericStringHere}";
$reg ="/({)($)(?=.*[a-z])(})/";

if (preg_match($reg, $string)) {
echo "Matched";
} else {
echo "Unmatched";
}
?>



thanks

JAY6390
01-29-2010, 03:06 PM
%\{\$([\da-z]+)\}%i

louislouis
01-29-2010, 03:34 PM
%\{\$([\da-z]+)\}%i

Doesn't work :(




$string = "{$abc}";
$reg ="%\{\$([\da-z]+)\}%i";

if (preg_match($reg, $string)) {
echo "Matched";
} else {
echo "Unmatched";
}



result: Unmatched

JAY6390
01-29-2010, 03:36 PM
The problem isn't the regex, it's your double quotes around the text. Changing it to single quotes will work. The reason is that PHP tries to substitute $abc for the variable $abc's value, which doesn't exist.
This works..

$string = '{$aaBBcc112233CCbbAA}';
$reg = '%\{\$([\da-z]+)\}%i';

if (preg_match($reg, $string)) {
echo "Matched";
} else {
echo "Unmatched";
}

Fou-Lu
01-29-2010, 03:39 PM
Looks ok offhand. Been awhile, and although it shouldn't make a difference, I question if the { and } need escaping in this pattern since the limiter wouldn't be valid. The only thing I can suggest is to replace the [\da-z]+ with \w+ to see if that works. \w will however include the _ in it as well, but if it works it may just be some wierdness with the \d to a chain. That could be solved with a [0-9a-z]+ pattern instead. That said, variables cannot start with a number, so if you're planning on later using an eval, you'll need to run it against: [a-z][\w]+


Ahah, good catch with the double quotes for expansion!

louislouis
01-29-2010, 03:56 PM
ahhhhhhhhh!! Thanks very much Jay!

JAY6390
01-29-2010, 04:06 PM
No problem. This is why error reporting should be on fully during development :) It would have told you the problem immediately



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum