加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

如何在php中返回正则表达式,而不是替换

发布时间:2020-12-13 16:26:02 所属栏目:PHP教程 来源:网络整理
导读:我试图在 HTML文本块中提取图像的第一个src属性,如下所示: Lorem ipsum img src="http://example.com/img.jpg" /consequat. 创建正则表达式以匹配src属性没有问题,但是如何返回第一个匹配的src属性,而不是替换它? 从倾注PHP手册,似乎preg_filter()会做的伎
我试图在 HTML文本块中提取图像的第一个src属性,如下所示:
Lorem ipsum <img src="http://example.com/img.jpg" />consequat.

创建正则表达式以匹配src属性没有问题,但是如何返回第一个匹配的src属性,而不是替换它?

从倾注PHP手册,似乎preg_filter()会做的伎俩,但我不能依赖最终用户具有PHP> 5.3.

所有其他PHP正则表达式函数似乎都是preg_match()的变体,返回一个布尔值,或者preg_replace,它替换了一些匹配项.有没有直接的方法来返回PHP中的正则表达式匹配?

您可以使用 preg_match的第三个参数来了解匹配项(它是一个数组,通过引用传递):
int preg_match  ( string $pattern,string $subject  [,array &$matches  [,int $flags  [,int $offset  ]]] )

If matches is provided,then it is
filled with the results of search.
$matches[0] will contain the text that
matched the full pattern,$matches[1]
will have the text that matched the
first captured parenthesized
subpattern,and so on.

例如,使用这部分代码:

$str = 'Lorem ipsum dolor sit amet,adipisicing <img src="http://example.com/img.jpg" />consequat.';

$matches = array();
if (preg_match('#<img src="(.*?)" />#',$str,$matches)) {
    var_dump($matches);
}

你会得到这个输出:

array
  0 => string '<img src="http://example.com/img.jpg" />' (length=37)
  1 => string 'http://example.com/img.jpg' (length=23)

(请注意,我的正则表达式过于简单 – 当从一些HTML字符串中提取数据时,正则表达式通常不是“正确的工具”).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读