Home  >  Article  >  Backend Development  >  Detailed explanation of the use of preg_match function in PHP (with code examples)

Detailed explanation of the use of preg_match function in PHP (with code examples)

autoload
autoloadOriginal
2021-04-16 14:25:418117browse

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

  • ##$offset: Optional parameter offset is used to specify Start searching from a certain position in the target string (unit is bytes).

  • Return value: number of matches. Its value will be 0 (no match) or 1 because preg_match() will stop matching after the first match. An error occurred preg_match() returned FALSE.

Usage example:

<?php

//从URL中获取主机名称
preg_match(&#39;@^(?:http://)?([^/]+)@i&#39;,
    "http://www.php.cn/index.html", $matches);
$host = $matches[1];

//获取主机名称的后面两部分
preg_match(&#39;/[^.]+\.[^.]+$/&#39;, $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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn