PHP - preg_match
Trieda
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ázov | Dátový typ | Predvolená hodnota | Popis |
|---|---|---|---|
| $pattern | string | The pattern to search for in the string. | |
| $subject | string | The input string. | |
| &$matches | array | If the
| |
| $flags | int | 0 | If we pass the |
| $offset | int | 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 string0- The pattern doesn't match the stringfalse- 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!';
}
