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

php regular expression (regar expression)_PHP tutorial

WBOY
Release: 2016-07-21 15:24:34
Original
940 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 Code The code is as follows:

$mode="/[^8s]/";//Matching module
$str="sssjj88d ";//Match content
echo "
";
if(preg_match($mode,$str,$arr)){ //Matching function
echo "Match successfully".$arr [0];//$arr[0]: The first value of the matching result set
}
else{
echo "match failed";
}

Result:
Regular expression 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 carriage return or line feed.
+ matches the previous content 1 or more times (except empty).
| The matching selection 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 }, indicates the number of times to match the previous content, which indicates the number of times from a to b.
( ) merges the overall match and puts it into memory. You can use 1 2... to get it in sequence
The following is an example I wrote in php:
Copy code The code is as follows:

$mode="/d{2,4}(.*)d{1,2}\1d{1,2 }/";//The simpler the matching module is, the better
//$mode="/2009(.*)9\1(10)/";
$str="2011/9/ 10";
if(preg_match($mode,$str,$arr)){
echo "Match successfully"."
".$arr[0 ]."

Happy Teacher's Day";
}
else{
echo "match failed";
}
?>

Result:

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/324272.htmlTechArticleIntroduction: When writing programs or web pages that process strings, it is often necessary to find characters that match certain complex rules. String needs. Regular expressions are the syntax used to describe these rules. ...
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