Home >Backend Development >PHP Tutorial >What is php regular expression? (code example)

What is php regular expression? (code example)

藏色散人
藏色散人Original
2019-04-18 13:40:142580browse

What is a regular expression?

Regex (or RegExp) stands for regular expression, which is a way to quickly and efficiently match patterns within a string method. Regex can be used for text search and replacement, input validation and other processes.

Regular expressions can be simple characters or complex patterns. All of these are defined under certain rules.

Regular Expressions in PHP

By default, PHP supports regex: PCRE (Perl Compatible Regular Expression) widely used syntax.

In PHP, the prefix of the PCRE (regular expression) function is preg_

PHP Regex replacement example:

<?php
$str = &#39;Hello World&#39;;
$regex = &#39;/\s/&#39;;
echo preg_replace($regex, &#39;&#39;, $str);

Output:

HelloWorld

In this example, the first space in "Hello World" is removed. Therefore, it will output "HelloWorld". Let's see what $regex and preg_replace() do.

preg_replace()Search for a string (using regex pattern) and replace it with another string.

$regexHelp search string. The

/

symbols at the beginning and end of $regex indicate the beginning and end of the regular expression. They are called separators.

\s is a single expression. It matches any space character. They are called character types.

Then, replace the match with ". Therefore, the spaces are removed.

Related recommendations: "PHP Tutorial"

The above is the detailed content of What is php regular expression? (code example). 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