Maison > php教程 > php手册 > le corps du texte

PHP preg_match正则表达式的使用

WBOY
Libérer: 2016-06-13 11:19:41
original
1207 Les gens l'ont consulté

在php中preg_match()函数是用来执行正则表达式的一个常用的函数,下面我来给大家详细介绍preg_match使用方法。  

函数用法

int preg_match_all ( string pattern, string subject, array matches [, int flags] )

例1

 代码如下 复制代码

preg_match_all ("|]+>(.*)]+>|U","example:

this is a test ",$out, PREG_SET_ORDER);
print $out[0][0].", ".$out[0][1]."n";
print $out[1][0].", ".$out[1][1]."n";
?>

 

本例将输出:
example: , example:

this is a test , this is a test

 

例2

URL 中取出域名

 代码如下 复制代码

// 从 URL 中取得主机名
preg_match("/^(http://)?([^/]+)/i", "http://www.***.net/index.html", $matches);
$host = $matches[2];
// 从主机名中取得后面两段
preg_match("/[^./]+.[^./]+$/", $host, $matches);
echo "domain name is: {$matches[0]}n";
?> 

本例将输出:

domain name is: PPP.NET

preg_match字符串长度问题

preg_match正则提取目标内容,死活有问题,代码测得死去活来。

后来怀疑PHP 的preg_match有字符串长度限制,果然,发现“pcre.backtrack_limit ”的值默认只设了100000。

解决办法:

 代码如下 复制代码
ini_set('pcre.backtrack_limit', 999999999);

注:这个参数在php 5.2.0版本之后可用。

另外说说关于:pcre.recursion_limit

pcre.recursion_limit是PCRE的递归限制,这个项如果设很大的值,会消耗所有进程的可用堆栈,最后导致PHP崩溃。

也可以通过修改配置来限制:

 代码如下 复制代码
ini_set('pcre.recursion_limit', 99999);

实际项目应用中,最好也对内存进行限定设置:ini_set('memory_limit', '64M'); , 这样就比较稳妥妥嘎。


Étiquettes associées:
source:php.cn
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Recommandations populaires
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!