欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  php教程

PHP基础教程之正则表达式

程序员文章站 2022-03-24 23:30:16
...

? $regex = '/^http:\/\/([\w.])\/([\w])\/([\w])\.html$/i' ; $str = 'http://www.youku.com/show_page/id_ABCDEFG.html' ; $matches = array(); if (preg_match($regex, $str, $matches)){ var_dump($matches); } echo \n ; preg_match中的$matches[0]将包

?

$regex = '/^http:\/\/([\w.]+)\/([\w]+)\/([\w]+)\.html$/i';

$str = 'http://www.youku.com/show_page/id_ABCDEFG.html';

$matches = array();

if(preg_match($regex, $str, $matches)){

var_dump($matches);

}

echo "\n";

preg_match中的$matches[0]将包含与整个模式匹配的字符串。

使用"#"定界符的代码如下.这个时候对"/"就不转义!

?

$regex = '#^http://([\w.]+)/([\w]+)/([\w]+)\.html$#i';

$str = 'http://www.youku.com/show_page/id_ABCDEFG.html';

$matches = array();

if(preg_match($regex, $str, $matches)){

var_dump($matches);

}

echo "\n";

¤ 修饰符:用于改变正则表达式的行为。

我们看到的('/^http:\/\/([\w.]+)\/([\w]+)\/([\w]+)\.html/i')中的最后一个"i"就是修饰符,表示忽略大小写,还有一个我们经常用到的是"x"表示忽略空格。

贡献代码:

?

$regex = '/HELLO/';

$str = 'hello word';

$matches = array();

if(preg_match($regex, $str, $matches)){

echo 'No i:Valid Successful!',"\n";

}

if(preg_match($regex.'i', $str, $matches)){

echo 'YES i:Valid Successful!',"\n";

}

¤ 字符域:[\w]用方括号扩起来的部分就是字符域。

¤ 限定符:如[\w]{3,5}或者[\w]*或者[\w]+这些[\w]后面的符号都表示限定符。现介绍具体意义。

{3,5}表示3到5个字符。{3,}超过3个字符,{,5}最多5个,{3}三个字符。

* 表示0到多个

+ 表示1到多个。

¤ 脱字符号

^:

> 放在字符域(如:[^\w])中表示否定(不包括的意思)——“反向选择”

> 放在表达式之前,表示以当前这个字符开始。(/^n/i,表示以n开头)。

注意,我们经常管"\"叫"跳脱字符"。用于转义一些特殊符号,如".","/"