preg_match_all, regular expression in php with variables

Asked

Viewed 216 times

0

Hello I’m having difficulties in mounting the regular expression, and the function returns me 3 positions in the array all empty;

preg_match_all('/<a data-role\="sku\" data-sku-id\="'.$the_new_id[2].'\" id\="sku\-3\-'.$the_new_id[2].'\" href\="javascript:void(0)\">(.*)<\a>/i', $page_content, $sku_3_a);

array(3) {
[0]=>
  array(0) {
  }
  [1]=>
  array(0) {
  }
  [2]=>
  array(0) {
  }
  • What is the string that you are using? What parts of string you want to capture?

  • The value inside the <a> tag: <the data-role="sku" data-sku-id="201301155" id="sku-3-201301155" href="javascript:void(0)"><span>32cm</span></a>

  • it seems that counted by the amount of items that is on the site, but did not return the content.

1 answer

1

It’s probably not working because you’re escaping the quotes unnecessarily. You only need to escape these quotes, when the function starts with them, for example

preg_match_all("necessário \" escapar", $var)

Otherwise

preg_match_all(' "Aqui" não precisa ', $var)

If you are trying to extract links from a page, just use the "Regex" below (shorter):

preg_match_all('/<a.*data-sku-id="'.$dataSkuId.'".*id="sku-\d-'.$yourId.'"[^>]*>(.*)<\/a>/i', $page_content, $sku_3_a);

If you want to get only the HTML value, just use strip_tags

strip_tags('<a data-role="sku" data-sku-id="201301155" id="sku-3-201301155" href="javascript:void(0)"><span>32cm</span></a>');

// Output: 32cm
  • Whoa, thanks for the example, I’m testing

Browser other questions tagged

You are not signed in. Login or sign up in order to post.