In dealing with some complex string can not handle clean with ordinary string handling functions, regular expressions have its uses.
Here to talk about the basic usage of regular expressions
<?php
int preg_match ($ modle, $ string) // first character string when the matching mode, the second string is the string to be matched, the function returns an integer value, returns a successful match, else return 0;
?>
The following is a quantifier matches pattern was used in the meta-characters ﹑ ﹑ modifier.
Take a look at the list of quantifiers
+ | Matches any string of characters comprises at least one preamble |
* | Zero or more matches any string of leading characters |
? | Matches any zero or a leading character string |
. | Matches any character (a character corresponding to a dot) |
{X, y} | Matches any preamble contains a string X to Y |
| | Matching string left or right |
$ | From the beginning of the end of the match |
^ | Begin at the beginning match |
A matching example:
<?php
$modle = '/ph+p/';
$string = 'php' ;
echo preg_match($modle,$string);
?>
This result seems to show: 1. After reading this example, other results quantifier usage is the same.
Take a look at the list of metacharacters
[a-z] | Matches any lowercase letter string from a to z |
[0-9] | Number matches any number from 0 to 9 |
[A-zA-Z0-9] | Matches any case from az, digits from a string of 0-9 (with [\ W] the same effect) |
There are several meta characters such as: [\ W] (with [\ W] Instead), \ S indicates a match blank character, \ S which is non-blank character match.
Application examples metacharacters
? <PHP
$ modle = '/([\w\_\.]{2,255})@([\w-]{1,}).([az]{2,4})/';
$ String = '[email protected]';
IF ( the preg_match ( $ modle , $ String ) ==. 1)
{ echo "message name normal";}
the else
{ echo "message name egg pain";}
>?
The above is a small mail format to determine the application, integrated application is the yuan characters.
The best look modifiers
i | Absolutely not case sensitive |
m | Before or after the multi-line mode matching |
x | Ignore spaces have to match the string |
A | Forced to start from scratch match |
The | Prohibit greedy problem |
Here is an example, too greedy for UUB resolve the problem
<? PHP
// The purpose of our simulation of this match is UUB parser, speak [b] [/ b] converted to <strong> </ strong> $ modle = '/ \ [b \] (. *) \ [\ / B \] / '; $ Replace =' <strong> \. 1 </ strong> '; $ String =' the this IS [B] Lili [/ b], that IS [B] Li Li [/ b] '; echo preg_replace ( $ modle , $ Replace , $ String ); echo "<br />"; $ modle =' /\[b\](.*)\[\/b\]/U '; $ Replace = '<strong> \. 1 </ strong>'; $ String = 'the this IS [B] Lili [/ B], that IS [B] Li Li [/ B]'; echo preg_replace ( $ modle , $ Replace ,$string)?>
I do not speak, the results at a glance ,, basic regular expressions on here, if you do not know what, leave a message ~ ~
Reproduced in: https: //www.cnblogs.com/dengwz7788/archive/2011/10/08/2202230.html