使用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)
// 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/
我得到了这段代码:
$dom = new DOMDocument();
$dom->loadHTML($img);
echo $dom->getElementsByTagName('img')->item(0)->getAttribute('src');
Run Code Online (Sandbox Code Playgroud)
假设只有一个img:P
| 归档时间: |
|
| 查看次数: |
58946 次 |
| 最近记录: |