preg_match与preg_match_all,是最常用的字符串匹配函数,用于从字符串提取信息。官方文档:preg_match、preg_match_all
preg_match,基础语法格式:
preg_match(
string $pattern, // 正则表达式
string $subject, // 目标字符串
array &$matches = null, // 匹配结果
int $flags = 0, //
int $offset = 0
): int|false
简单使用,从“$53 /yr”字符串中提取价格
<?php
$pattern = "/[0-9]+/";
$subject='$53 /yr';
$m1 =preg_match($pattern,$subject,$arr1);
echo $m1.'<br>'; // 1
echo $arr1[0]; // 53
在这个例子中,arr1[0]保存匹配结果,而返回值m1要么0表示找不到,1表示找到。
preg_match_all函数语法格式相同,它会匹配所有,可能得到多个值,arr1[0]表示第一个得到的结果,arr1[1]表示得到的第二个结果,以此类推
本篇完,还有疑问?留下评论吧