php regex:获取src值

时间:2009-03-30 04:20:07

标签: php regex

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

<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>

检索到的值应仅包含:

谢谢。

5 个答案:

答案 0 :(得分:7)

/src=(["'])(.*?)\1/

示例:

<?php

$input_string = '<script type="text/javascript" src="http://localhost/assets/javascript/system.js" charset="UTF-8"></script>';
$count = preg_match('/src=(["\'])(.*?)\1/', $input_string, $match);
if ($count === FALSE) 
    echo('not found\n');
else 
    echo($match[2] . "\n");

$input_string = "<script type='text/javascript' src='http://localhost/index.php?uid=93db46d877df1af2a360fa2b04aabb3c' charset='UTF-8'></script>";
$count = preg_match('/src=(["\'])(.*?)\1/', $input_string, $match);
if ($count === FALSE) 
    echo('not found\n');
else 
    echo($match[2] . "\n");

给出:

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

答案 1 :(得分:7)

也许只是我,但我不喜欢使用正则表达式来查找HTML中的内容,特别是当HTML无法预测时(可能来自用户或其他网页)。

这样的事情怎么样:

$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 );

我不知道这与正则表达式之间的速度差异是什么,但是我花了很多时间阅读它并理解我正在尝试做什么。

答案 2 :(得分:4)

我同意Nick,使用DomDocument对象来获取数据。这是一个xpath版本:

$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;

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

$xpath = new DomXpath($doc);
$elements = $xpath->query('//[@src]');

foreach($elements as $element)
{
    echo $element->nodeValue;
}

答案 3 :(得分:0)

如果您决定使用正则表达式路线,这应该对您有用

/(?<=\<).*?src=(['"])(.*?)\1.*?(?=/?\>)/si

答案 4 :(得分:0)

jQuery方法

var Scripts = [];
$('head script').each(function(){
    if($(this).attr('type') == 'text/javascript' && $(this).attr('src')){
        Scripts.push($(this).attr('src'));
    }
});
console.log(Scripts)