PHP preg_match() Functie
Voorbeeld
Gebruik een reguliere expressie om hoofdletterongevoelig te zoeken naar "w3schools" in een string:
<?php
$str = "Visit W3Schools";
$pattern = "/w3schools/i";
echo
preg_match($pattern, $str);
?>
Definitie en gebruik
De preg_match()
functie retourneert of er een overeenkomst is gevonden in een tekenreeks.
Syntaxis
preg_match(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:
|
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 1 als er een overeenkomst is gevonden, 0 als er geen overeenkomsten zijn gevonden en onwaar als er een fout is opgetreden |
---|---|
PHP-versie: | 4+ |
Wijzigingslogboek: | PHP 7.2 - Toegevoegd de PREG_UNMATCHED_AS_NULL vlag PHP 5.3.6 - De functie retourneert false wanneer de offset langer is dan de lengte van de invoer PHP 5.2.2 - Benoemde subpatronen kunnen de (?'name') en (? <name>) gebruiken syntaxis naast de vorige (?P<naam>) |
Meer voorbeelden
Voorbeeld
Gebruik PREG_OFFSET_CAPTURE om de positie in de invoerreeks te vinden waarin de overeenkomsten zijn gevonden:
<?php
$str = "Welcome to W3Schools";
$pattern = "/w3schools/i";
preg_match($pattern, $str, $matches, PREG_OFFSET_CAPTURE);
print_r($matches);
?>
❮ PHP RegExp-referentie