正则表达式和PHP - 从img标签中隔离src属性

Jef*_*eff 35 php regex string

使用PHP,我如何从$ foo中隔离src属性的内容?我正在寻找的最终结果只会给我" http://example.com/img/image.jpg "

$foo = '<img class="foo bar test" title="test image" src="http://example.com/img/image.jpg" alt="test image" width="100" height="100" />';
Run Code Online (Sandbox Code Playgroud)

Joh*_*ker 70

如果您不希望使用正则表达式(或任何非标准PHP组件),使用内置DOMDocument类的合理解决方案如下:

<?php
    $doc = new DOMDocument();
    $doc->loadHTML('<img src="http://example.com/img/image.jpg" ... />');
    $imageTags = $doc->getElementsByTagName('img');

    foreach($imageTags as $tag) {
        echo $tag->getAttribute('src');
    }
?>
Run Code Online (Sandbox Code Playgroud)


St.*_*and 35

<?php
    $foo = '<img class="foo bar test" title="test image" src="http://example.com/img/image.jpg" alt="test image" width="100" height="100" />';
    $array = array();
    preg_match( '/src="([^"]*)"/i', $foo, $array ) ;
    print_r( $array[1] ) ;
Run Code Online (Sandbox Code Playgroud)

产量

http://example.com/img/image.jpg
Run Code Online (Sandbox Code Playgroud)


kar*_*m79 7

// Create DOM from string
$html = str_get_html('<img class="foo bar test" title="test image" src="http://example.com/img/image.jpg" alt="test image" width="100" height="100" />');

// echo the src attribute
echo $html->find('img', 0)->src;
Run Code Online (Sandbox Code Playgroud)

http://simplehtmldom.sourceforge.net/


Ant*_*oCS 7

我得到了这段代码:

$dom = new DOMDocument();
$dom->loadHTML($img);
echo $dom->getElementsByTagName('img')->item(0)->getAttribute('src');
Run Code Online (Sandbox Code Playgroud)

假设只有一个img:P