php regex:获取src值 [英] php regex : get src value

查看:59
本文介绍了php regex:获取src值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在php中使用正则表达式检索所有src值?

How do I retrieve all src value using regex in php?

<script type="text/javascript" src="http://localhost/assets/javascript/system.js" charset="UTF-8"></script>
<script type='text/javascript' src='http://localhost/index.php?uid=93db46d877df1af2a360fa2b04aabb3c' charset='UTF-8'></script>

检索到的值应仅包含:

  • http://localhost/assets/javascript/system.js
  • http://localhost/index.php?uid=93db46d877df1af2a360fa2b04aabb3c

谢谢.

推荐答案

也许只是我一个人,但我不喜欢使用正则表达式在HTML片段中查找内容,尤其是在HTML不可预测的情况下(也许来自用户或其他网页).

Maybe it is just me, but I don't like using regular expressions for finding things in pieces of HTML, especially when the HTML is unpredictable (perhaps comes from a user or other web pages).

怎么样呢?

$doc =
<<<DOC
    <script type="text/javascript" src="http://localhost/assets/javascript/system.js" charset="UTF-8"></script>
    <script type='text/javascript' src='http://localhost/index.php?uid=93db46d877df1af2a360fa2b04aabb3c' charset='UTF-8'></script>

DOC;

$dom = new DomDocument;
$dom->loadHTML( $doc );

$elems = $dom->getElementsByTagName('*');

foreach ( $elems as $elm ) {
    if ( $elm->hasAttribute('src') )
        $srcs[] = $elm->getAttribute('src');
}

print_r( $srcs );

我不知道此表达式与正则表达式之间的速度差是多少,但是花了我少得多的时间来阅读它并了解我要执行的操作.

I don't know what the speed difference is between this and a regular expression but it takes me a heck of a lot less time to read it and understand what I'm trying to do.

这篇关于php regex:获取src值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆