Return all results using preg_match

Asked

Viewed 324 times

0

I need to return some search results "ex: Digital Agency" from the first page of Google using preg_match + Regex, but it is not returning all 10 values in the array, only the first. How do I resolve?

Ex:

$document = file_get_contents('https://www.google.com/search?q=Ag%C3%AAncia+Digital');

preg_match_all('/<li class=\"g\">([^`]*?)<\/li>/', $document, $matches);

print_r($matches);
  • I tested your code here, came an array with two keys and 10 elements (html) in each but I had to use the option to display browser source code.

1 answer

0


When syntactically parsing the HTML of a page with Regular Expressions, unfortunately being specific can be a problem.

In such cases you should capture everything that is within a specific content delimiter, in your case the <li></li>. And because of the ? in your group you undo quantifier’s greed *.

Literally, it’s like you’re saying: Anything that’s not a backtick, in any amount, but if you don’t have any, that’s fine too.

So much so that it was enough to remove the question mark and all the other results appeared.

Browser other questions tagged

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