NOVINKA: Najžiadanejšie rekvalifikačné kurzy teraz s 50% zľavou + kurz AI ZADARMO. Nečakaj, táto ponuka dlho nevydrží! Zisti viac:

PHP - preg_match

Trieda

Koreň \ Bez triedy

Metóda - preg_match

(PHP 4, PHP 5, PHP 7)

The preg_match() function is used for finding a match of a string with a regular expression pattern.

Warning: For testing the return value use the === operator to avoid problems with misinterpreting the false and 0 values.

Note: Don't use the preg_match() function to determine whether a string contains a substring. For these intends, use mb_strpos().

Procedurálne

  • function preg_match (string $pattern, string $subject, array &$matches, int $flags = 0, int $offset = 0) : int

Parametre

NázovDátový typPredvolená hodnotaPopis
$patternstring

The pattern to search for in the string.

$subjectstring

The input string.

&$matchesarray

If the $matches variable is passed, it's filled with the search results .

  • $matches[0] contains a string suitable to the full pattern
  • $matches[1], ... the other indexes contain matched strings from the parenthesized subpatterns
$flagsint 0

If we pass the PREG_OFFSET_CAPTURE value, the $matches items will be arrays of 2 keys. The 0 key will contain the given substring and the key 1 its position in the main string.

$offsetint 0

If we specify the parameter, the search will not start from the beginning of the string, but the given number of bytes will be skipped.

Mávratovej hodnoty

Vracia: int

The function can return 3 different values. Be sure to handle the values 0 and false correctly! Use the === operator to do so.

  • 1 - The pattern matches the string
  • 0 - The pattern doesn't match the string
  • false - An error has occurre

Príklady

A simplified finding of individual email's parts:

<?php
echo '<pre>';
preg_match('/(.*)@(.*)\.(.*)/', '[email protected]', $matches); // finds individual parts of the email
print_r($matches);

preg_match('/(.*)@(.*)\.(.*)/', '[email protected]', $matches, PREG_OFFSET_CAPTURE); // finds individual parts of the email and their positions
print_r($matches);
echo '</pre>';

A practical usage for validating the user's nickname:

<?php
$nickname = 'Jack';
if (preg_match('/\A[A-Za-z0-9]{4,16}\z/', $nickname)) {
    echo 'Nickname "' . $nickname . '" is valid!';
} else {
    echo 'Nickname "' . $nickname . '" is invalid!';
}

echo '<br>';

$nickname = 'El Banana';
if (preg_match('/\A[A-Za-z0-9]{4,16}\z/', $nickname)) {
    echo 'Nickname "' . $nickname . '" is valid!';
} else {
    echo 'Nickname "' . $nickname . '" is invalid!';
}

Súvisiace manuály

        Aktivity