正则表达式用相应的<img>替换<a>

0 php regex preg-replace

我正在寻找一个PHP preg_replace()解决方案找到图像的链接,并用相应的图像标签替换它们.

找:

<a href="http://www.domain.tld/any/valid/path/to/imagefile.ext">This will be ignored.</a>
Run Code Online (Sandbox Code Playgroud)

用...来代替:

<img src="http://www.domain.tld/any/valid/path/to/imagefile.ext" alt="imagefile" />
Run Code Online (Sandbox Code Playgroud)

协议必须是http://,.ext必须是有效的图像格式(.jpg,.jpeg,.gif,.png,.tif),基本文件名称变为alt =""值.

我知道preg_replace()是这项工作的正确功能,但我很喜欢正则表达式,所以非常感谢任何帮助!谢谢!

bob*_*nce 10

恭喜,您是第100个客户,要求Stack Overflow如何使用正则表达式解析HTML!

[X] [HT] ML不是常规语言,无法使用正则表达式进行可靠的解析.使用HTML解析器.PHP本身为您提供DOMDocument,或者您可能更喜欢simplehtmldom.

顺便说一句,您无法通过查看其URL来确定文件的类型.JPEG没有理由将'.jpeg'作为其扩展名 - 实际上,不能保证扩展名为'.jpeg'的文件实际上是JPEG.唯一可靠的方法是获取资源(例如,使用HEAD请求)并查看Content-Type标头.


med*_*iev 7

啊,我每天的DOM练习.您应该使用DOM来解析HTML和正则表达式来解析诸如html属性之类的字符串.

注意:我有一些基本的正则表达式肯定可以通过一些向导来改进:)

注意#2:虽然它可能是额外的开销,但您可以使用像curl这样的东西通过发送HEAD请求并查看Content-Type来彻底检查href是否是实际图像,但这在80-90%的情况下有效.

<?php

$content = '

<a href="http://www.domain.tld/any/valid/path/to/imagefile.ext">This will be ignored.</a>
<br>

<a href="http://col.stb.s-msn.com/i/43/A4711309495C88F8CD154C99FCE.jpg">this will not be ignored</a>

<br>

<a href="http://col.stb.s-msn.com/i/A0/8E9A454F701E4F5F89E58E14B532C.jpg">bah</a>
';

$dom = new DOMDocument();
$dom->loadHTML($content);

$anchors = $dom->getElementsByTagName('a');

$i = $anchors->length-1;

$protocol = '/^http:\/\//';
$ext = '/([\w+]+)\.(?:gif|jpg|jpeg|png)$/';

if ( count($anchors->length) > 0 ) {
    while( $i > -1 ) {
    $anchor = $anchors->item($i);
    if ( $anchor->hasAttribute('href') ) {
        $link = $anchor->getAttribute('href');

        if ( 
        preg_match ( $protocol , $link ) &&
        preg_match ( $ext, $link )
        ) {
        //echo 'replacing this one.';
        $image = $dom->createElement('img');

        if ( preg_match( $ext, $link, $matches ) ) {
            if ( count($matches) ) {
            $altName = $matches[1];
            $image->setAttribute('alt', $altName);
            }
            $image->setAttribute('src', $link);
            $anchor->parentNode->replaceChild( $image, $anchor );
        }
        }

    }
    $i--;
    }
}

echo $dom->saveHTML();
Run Code Online (Sandbox Code Playgroud)

  • 正则表达式解决方案太容易失败,我会坚持使用DOM但是谢谢. (4认同)
  • 此外,DOM解决方案更灵活,因为您可以执行任何您想要的DOM操作,您在正则表达式替换方面受到限制. (2认同)