php用正则表达抓取网页中文章(本文实例讲述PHPpreg_实现正则表达式匹配功能(图) )
优采云 发布时间: 2022-02-23 19:21php用正则表达抓取网页中文章(本文实例讲述PHPpreg_实现正则表达式匹配功能(图)
)
本文中的例子描述了PHP preg_match 中正则表达式匹配的实现。分享给大家,供大家参考,如下:
preg_match — 执行正则表达式匹配
preg_match ( $pattern , $subject , $matches )
搜索主题以匹配由模式给出的正则表达式。
参数:
pattern : 要搜索的模式,字符串类型(正则表达式)。
subject : 输入字符串。
matches :(可选)如果提供了参数匹配,它将作为搜索结果填充。 $matches[0] 将收录完整模式匹配的文本,$matches[1] 将收录第一个捕获子组匹配的文本,依此类推。
返回值:
preg_match() 返回模式的匹配数。其值为 0(不匹配)或 1,因为 preg_match() 将在第一次匹配后停止搜索。 preg_match_all() 与此不同之处在于它搜索主题直到它到达结尾。如果发生错误 preg_match() 返回 FALSE。
示例 1:
$label = 'content/112';
$a = preg_match('#content/(\d+)#i', $label, $mc);
var_dump($a);
var_dump($mc);
输出:
int(1)
array(2) {
[0]=>
string(11) "content/112"
[1]=>
string(3) "112"
}
示例 2:
$label = 'content/112';
$a = preg_match('#(\w+)/(\d+)#i', $label, $mc);
var_dump($a);
var_dump($mc);
输出:
int(1)
array(3) {
[0]=>
string(11) "content/112"
[1]=>
string(7) "content"
[2]=>
string(3) "112"
}
示例 3:
$label = 'content/112';
$a = preg_match('#content1111111/(\d+)#i', $label, $mc);
var_dump($a);
var_dump($mc);
输出:
int(0)
array(0) {
}
以上是php正则表达式preg_match是如何实现匹配功能的?更多详情请关注php中文网其他相关话题文章!