Home >Backend Development >PHP Tutorial >regularexpression php regular expression regar expression

regularexpression php regular expression regar expression

WBOY
WBOYOriginal
2016-07-29 08:46:451066browse

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]: Match the first value of the result set
}
else{
echo "Match failed";
}


Result:
 php正则表达式regar expressionRegular expression (regular expression) "metacharacter":
* matches 0 or more times of the previous content, that is, before Matches any content
. Matches 0 times, 1 or more times of the content, but does not include carriage returns and line feeds
+ Matches 1 or more times of the previous content (except empty).
| The selection match is similar to | in PHP (because this operator is a weak type, so the front is 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, the better
//$mode="/2009 (.*)9\1(10)/";
$str="2011/9/10";
if(preg_match($mode,$str,$arr)){
echo "Match successfully"."< ;br/>".$arr[0]."

";
}
else{
echo "Match failed";
}
?>


Result:

 php正则表达式regar expression

The above introduces the regular expression php regular expression regar expression, including the content of regular expression. I hope it will be helpful to friends who are interested in PHP tutorials.

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