MrG
MrG

Reputation: 95

preg_match pattern variable usage

I tried searching here and Google, but couldn't find a solution to the following:

$picUrl = '"thumbs/phpThumb.php?src=../property-photos/50/2485/068cf6589a9fb13065818efef3d1e1c0-small.jpg&w=80&h=60&far=1&bg=EEEEEE"';
$number = "2485";
$expression = "'#".$number."/(.*?)&w#'";
echo "<b>expression is </b>".$expression."<br />";
echo "<b>picUrl is </b>".$picUrl."<br />";
preg_match($expression, $picUrl, $pic);  //'#2485/(.*?)&w#'
//if($pic) echo "pic is ".$pic[1]."<br />";
echo "<b>contents of pic array</b>".var_dump($pic);

As written above, the array is empty. However, if I replace the $expression variable in the preg_match function, with the text following the php comment (ie: '#2485/(.*?)&w#'), I get the desired result.

Why is the use of the $expression variable not working?

Upvotes: 1

Views: 1508

Answers (2)

Martin Ender
Martin Ender

Reputation: 44289

$expression is a string starting with and ending with '. Thus, ' becomes the delimiter, and # becomes a literal in your regex. '#2485/(.*?)&w#' is a string starting and ending with # which now is a delimiter of the regex and not a literal.

Simply use either this:

$expression = "#".$number."/(.*?)&w#";

or (which I recommend) this:

$expression = '#'.$number.'/(.*?)&w#';

Upvotes: 1

Michal Fabry
Michal Fabry

Reputation: 19

Remove single quotes from your $expression:

$expression = "#".$number."/(.*?)&w#";

Upvotes: 0

Related Questions