Limit the number of results using preg_match_all PHP

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

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

Greetings

+3
source share
5 answers

No, the calculation of a result set preg_match_allcannot be limited. You can limit the results later array_sliceor array_splice(this requires PREG_SET_ORDER):

preg_match_all($pattern, $subject, $matches, PREG_SET_ORDER);
$firstMatches = array_slice($matches, 0, 20);

, HTML. , HTML, . HTML-, , DOM PHP. , 20 :

$doc = new DOMDocument();
$doc->loadHTML($code);
$counter = 20;
$matches = array();
foreach ($doc->getElementsByTagName('p') as $elem) {
    if ($counter-- <= 0) {
        break;
    }
    $matches[] = $elem;
}
+4
$matches = array();   
preg_match_all ( $pattern , $subject , $matches );
$twenty = array_slice($matches , 0, 20);
+3

:

$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
+3

, preg_match offset, PREG_OFFSET_CAPTURE, , " ".

, , array_slice() : o)

EDIT: , - ( - ):

$offset = 0;
$matches = array();
for ($i = 0; $i < 20; $i++) {
    $results = preg_match('/<p(?:.*?)>/', $string, PREG_OFFSET_CAPTURE, $offset);
    if (empty($results)) {
        break;
    } else {
        $matches[] = $results[0][0];
        $offset += $results[0][1];
    }
}
0

You can use preg_match_all()and discard matches that you are not interested in, or use a loop with preg_match(). The second option would be better if you were worried about the cost of scanning a large string.

This example is limited to two matches when there are actually 3 in the entire row:

<?php

$str = "ab1ab2ab3ab4c";

for ($offset = 0, $n = 0;
        $n < 2 && preg_match('/b([0-9])/', $str, $matches, PREG_OFFSET_CAPTURE, $offset);
        ++$n, $offset = $matches[0][1] + 1) {

        var_dump($matches);
}

Indeed, the loop would whileprobably be clearer than the forreflection loop ;)

0
source

Source: https://habr.com/ru/post/1780848/


All Articles