Home  >  Article  >  Backend Development  >  What is the use of php regular expressions

What is the use of php regular expressions

(*-*)浩
(*-*)浩Original
2019-09-12 09:30:182497browse

When do we use regular expressions? It is not enough to use regular expressions for all character operations. PHP uses regular expressions in some aspects, which actually affects efficiency. When we encounter complex text data parsing, regular expressions are a better choice.

What is the use of php regular expressions

Advantages

Regular expressions can improve work efficiency and save you to a certain extent when processing complex character operations. amount of code.

Disadvantages

When we use regular expressions, complex regular expressions will increase the complexity of the code and make it difficult to understand. So sometimes we need to add comments inside regular expressions.

General mode (Recommended learning: PHP programming from entry to proficiency)

Delimiter, usually use "/" as a delimiter characters at the beginning and end, you can also use "#".

When should you use "#"? Usually when there are many "/" characters in your string, because such characters need to be escaped when using regular expressions, such as uri.

The code using the "/" delimiter is as follows.

$regex = '/^http:\/\/([\w.]+)\/([\w]+)\/([\w]+)\.html$/i';
$str = 'http://www.youku.com/show_page/id_ABCDEFG.html';
$matches = array();

if(preg_match($regex, $str, $matches)){
    var_dump($matches);
}

echo "\n";

$matches[0] in preg_match will contain the string matching the entire pattern.

The code using the "#" delimiter is as follows. At this time, "/" is not escaped!

$regex = '#^http://([\w.]+)/([\w]+)/([\w]+)\.html$#i';
$str = 'http://www.youku.com/show_page/id_ABCDEFG.html';
$matches = array();

if(preg_match($regex, $str, $matches)){
    var_dump($matches);
}

echo "\n";

The definition of regular expressions can be simply summarized like this: "Regular The expression describes a string matching pattern, through which the string is matched, searched, replaced and split in a specific function. As a matching template, it is composed of atoms, special function characters and pattern modifiers Three-part text pattern.

The above is the detailed content of What is the use of php regular expressions. 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