Home >Backend Development >PHP Tutorial >Detailed explanation of the use of preg_match function in PHP (with code examples)
This article introduces the preg_match()
function in PHP
in more detail, supplemented by examples, so that everyone can take a look. preg_match()
function, how to match regular expression
.
Syntax:
preg_match ( string $pattern , string $subject ,array &$matches = ? ,int $flags = 0 ,int $offset = 0 )
$pattern: Pattern to search, string type.
$subject: Input string.
$matches: If the parameter matches is provided, it will be populated as search results. $matches[0] will contain the text matched by the complete pattern, $matches[1] will contain the text matched by the first captured subgroup, and so on.
$flags: Can be set to a combination of the following tag values: PREG_UNMATCHED_AS_NULL, PREG_OFFSET_CAPTURE
Usage example:
<?php //从URL中获取主机名称 preg_match('@^(?:http://)?([^/]+)@i', "http://www.php.cn/index.html", $matches); $host = $matches[1]; //获取主机名称的后面两部分 preg_match('/[^.]+\.[^.]+$/', $host, $matches); echo "admin name is: {$matches[0]}\n"; ?>
输出:admin name is: php.cn
Recommendation: 《2021 Summary of annual PHP interview questions (collection)》《php video tutorial》
The above is the detailed content of Detailed explanation of the use of preg_match function in PHP (with code examples). For more information, please follow other related articles on the PHP Chinese website!