Home > Backend Development > PHP Tutorial > php regular expression (regar expression)

php regular expression (regar expression)

高洛峰
Release: 2023-03-01 13:24:02
Original
1072 people have browsed it

Introduction: When writing programs or web pages that process strings, there is often a need to find strings that match certain complex rules

. Regular expressions are the syntax used to describe these rules.
Example: When judging the user's email address format, mobile phone number format, or collecting the content of other people's web pages.
PHP also often uses regular expressions. PHP has two commonly used regular expression functions: preg_match and ereg.
I just watched preg_match today. Its specific writing method is preg_match (mode, string subject, array matches);
The following is an example I wrote.
Copy the code The code is as follows:
$mode="/ [^8s]/";//Matching module
$str="sssjj88d";//Matching content
echo "


";
if(preg_match($mode,$str,$arr)){ // Matching function
echo "Match successful".$arr[0];//$arr[0]: The first value of the matching result set
}
else{
echo "Match failed";
}

Result:
Regular expression (regular expression) "metacharacter":
* matches 0 or more times of the previous content, that is, any previous content matches
. Matches 0 times, 1 or more times of the content, but does not include a carriage return Line break
+ matches the previous content 1 or more times (except empty).
| The selection match is similar to | in PHP (because this operator is a weak type, resulting in the most overall match)
^ matches the first content of the string
$ matches the last content of the string
{a,b}, which means matching the previous content The number of times, this means the number of times from a to b.
() Merge the overall match and put it into memory, you can use 1 2... to obtain it in sequence
The following is an example I wrote in php:
Copy the code The code is as follows:
$mode="/d{2 ,4}(.*)d{1,2}\1d{1,2}/";//The simpler the matching module is generally written, the better
//$mode="/2009(.*)9\1 (10)/";
$str="2011/9/10";
if(preg_match($mode,$str,$arr)){
echo "Match successfully"."
< font color=red>".$arr[0]."

Happy Teachers' Day";
}
else{
echo "Match failed";
}
?>

Related labels:
php
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template