Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limit the number of results using preg_match_all PHP

Is there any way to limit the number of matches that will be returned using preg_match_all?

So for example, I want to match only the first 20 <p> tags on a web page but there are 100 <p> tags.

Cheers

like image 313
Franco Avatar asked Dec 17 '22 19:12

Franco


2 Answers

$matches = array();   
preg_match_all ( $pattern , $subject , $matches );
$twenty = array_slice($matches , 0, 20);
like image 104
Moak Avatar answered Dec 27 '22 11:12

Moak


Just match all and slice the resulting array:

$allMatches = array ();
$numMatches = preg_match_all($pattern, $subject, $allMatches, PREG_SET_ORDER);
$limit = 20;
$limitedResults = $allMatches;
if($numMatches > $limit)
{
   $limitedResults = array_slice($allMatches, 0, $limit);
}

// Use $limitedResults here
like image 40
PatrikAkerstrand Avatar answered Dec 27 '22 11:12

PatrikAkerstrand