0
$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?

Thamaraiselvam
  • 6,961
  • 8
  • 45
  • 71

1 Answers1

1

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);
jens1o
  • 625
  • 7
  • 14
  • For some reason the alternative solution doesn't work me! I don't like using double quotes for text in PHP, therefore I prefer to concat single quoted text with vars using the dot symbol. But last time I tried this, preg_match literally searched for the single quote character as part of the pattern!!! This was my code... `preg_match_all('/[^' . $tron->separator . ']+' . $tron->separator . '[^' . $tron->separator . ']+/u', $tron->getAkas(), $outer);` – Peter K. May 30 '21 at 02:54