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?

3
  • 2
    Use double quotes. You can't interpolate variables inside single quoted string literals. Commented Oct 3, 2017 at 11:27
  • @WiktorStribiżew That solved the issue, Post-it as the answer Commented Oct 3, 2017 at 11:30
  • 1
    This is a dupe of too many questions, no need to post an answer. Commented Oct 3, 2017 at 11:31

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

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);

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.