Dexter Dexter - 3 years ago 220
PHP Question

How to use a php variable inside preg_match?

$pId = "MP000000001648426";

Below code is not working. Whats wrong with it?

preg_match_all('/<span id="price_$pId".*?>(.*?)\<\/span>/', $product ,$matches);

But, when I directly add the string (pId) to preg_match it works.

preg_match_all('/<span id="price_MP000000001648426".*?>(.*?)\<\/span>/', $product ,$matches);

But I want to provide a variable inside the preg match. How to do it?

Answer Source

change it to

preg_match_all("/<span id=\"price_$pId\".*?>(.*?)\<\/span>/", $product, $matches);

(note that you need real " so that PHP Variables are converted)

Alternative solution:

preg_match_all('/<span id="price_'. $pId . '".*?>(.*?)\<\/span>/', $product, $matches);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download