PHP preg_match_all() Functie
Voorbeeld
Zoek alle exemplaren van "ain" in een string:
<?php
$str = "The rain in SPAIN falls mainly on the plains.";
$pattern =
"/ain/i";
if(preg_match_all($pattern, $str, $matches)) {
print_r($matches);
}
?>
Definitie en gebruik
De preg_match_all()
functie retourneert het aantal overeenkomsten van een patroon dat in een tekenreeks is gevonden en vult een variabele met de gevonden overeenkomsten.
Syntaxis
preg_match_all(pattern, input, matches, flags, offset)
Parameterwaarden
Parameter | Description |
---|---|
pattern | Required. Contains a regular expression indicating what to search for |
input | Required. The string in which the search will be performed |
matches | Optional. The variable used in this parameter will be populated with an array containing all of the matches that were found |
flags | Optional. A set of options that change how the matches array is structured. One of the following structures may be selected:
|
offset | Optional. Defaults to 0. Indicates how far into the string to begin searching. The preg_match() function will not find matches that occur before the position given in this parameter |
Technische details
Winstwaarde: | Retourneert het aantal gevonden overeenkomsten of onwaar als er een fout is opgetreden |
---|---|
PHP-versie: | 4+ |
Wijzigingslogboek: | PHP 7.2 - Toegevoegd de PREG_UNMATCHED_AS_NULL vlag PHP 5.4 - De match parameter werd optioneel PHP 5.3.6 - De functie retourneert false wanneer de offset langer is dan de lengte van de input PHP 5.2.2 - Benoemde subpatronen kunnen de (?'name' gebruiken ) en (? <naam>) syntaxis naast de vorige (?P<naam>) |
Meer voorbeelden
Voorbeeld
Gebruik PREG_PATTERN_ORDER om de structuur van de overeenkomstenreeks in te stellen . In dit voorbeeld heeft elk element in de overeenkomstenreeks alle overeenkomsten voor een van de groeperingen van de reguliere expressie.
<?php
$str = "abc ABC";
$pattern = "/((a)b)(c)/i";
if(preg_match_all($pattern,
$str, $matches, PREG_PATTERN_ORDER)) {
print_r($matches);
}
?>
❮ PHP RegExp-referentie