简体   繁体   English

正在获取img标签,它是src值

[英]fetching img tag, and it's src value

I have 2 image tags, one after another 我有2个图片标签,一个接一个

<img class="c1 c2 c3" title="Image Title 1" src="http://example.com/image-1.jpg" alt="" width="620" height="521"><img class="c1 c2 c3" title="Image Title 2" src="http://example.com/image-2.jpg" alt="" width="620" height="521">

I want a regular expression that can fetch 2 things: 我想要一个可以获取2件事的正则表达式:

  • First 'img' tag 第一个“ img”标签
  • 'src' value from first 'img' tag 来自第一个'img'标签的'src'值

How can I do it? 我该怎么做?

PS do someone know where I can test regular expression online PS有人知道我可以在哪里在线测试正则表达式

Regular expression to match the first IMG tag and its src value: 正则表达式以匹配第一个IMG标签及其src值:

$subject = '<img class="c1 c2 c3" title="Image Title 1" src="http://example.com/image-1.jpg" alt="" width="620" height="521"><img class="c1 c2 c3" title="Image Title 2" src="http://example.com/image-2.jpg" alt="" width="620" height="521">';
preg_match('/<img\s.*?\bsrc="(.*?)".*?>/si', $subject, $matches);
print_r($matches);

Output: 输出:

Array
(
    [0] => <img class="c1 c2 c3" title="Image Title 1" src="http://example.com/image-1.jpg" alt="" width="620" height="521">
    [1] => http://example.com/image-1.jpg
)

There are many tools to test regular expressions online. 有很多工具可以在线测试正则表达式。 Here are just a few of them: 这里只是其中一些:

Is there any special reason why you want to use a regular expression over more, generally, suitable tools like the DOM extension ? 您是否有任何特殊原因想要在更多更合适的工具(例如DOM扩展)上使用正则表达式?

A basic example of getting the first <img> 's src attribute might look like: 获取第一个<img>src属性的基本示例如下所示:

$subject = '<img class="c1 c2 c3" title="Image Title 1" src="http://example.com/image-1.jpg" alt="" width="620" height="521"><img class="c1 c2 c3" title="Image Title 2" src="http://example.com/image-2.jpg" alt="" width="620" height="521">';
$doc = new DOMDocument;
$doc->loadHTML($subject);
$imgs = $doc->getElementsByTagName('img');
// Echo first <img>'s src attribute if we found any <img>s
if ($imgs->length > 0) {
    echo $imgs->item(0)->getAttribute('src');
}

使用: preg_match('/<img [>]*src="([^"]*)"/i',$subject,$matches);

Try something like /(<img[^>]*)/ to get the first img tag(or any using backreference). 尝试类似/(<img[^>]*)/来获取第一个img标签(或任何使用反向引用的标签)。 And then use something like /src="([^"])/ to get src from tag string. 然后使用类似/src="([^"])/方式从标记字符串获取src。

Answer to ps: http://www.spaweditor.com/scripts/regex/ 回答ps: http//www.spaweditor.com/scripts/regex/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM