用正则表达式链接替换iframe

时间:2016-04-05 08:48:33

标签: php regex

我目前有这个字符串:

"<p><iframe allowfullscreen="" class="media-element file-default" data-fid="2219" data-media-element="1" frameborder="0" height="360" src="https://www.youtube.com/embed/sNEJOm4hSaw?feature=oembed" width="640"></iframe></p>"

我想删除整个iframe元素(<iframe>...</iframe>),并将其替换为<a>属性中的网址的src链接:

<p><a href="https://www.youtube.com/embed/sNEJOm4hSaw?feature=oembed">Link to youtube</a></p>

目前,我有这个正则表达式:

$res = preg_replace('/src="(.+?)"/', '/<a href="$1">Link to youtube</a>/', $str);

使用此正则表达式,我可以使用src元素替换a属性。但是,我想替换整个iframe元素。

实现这一目标的最简单方法是什么?

3 个答案:

答案 0 :(得分:4)

使用此RegEx:

<iframe\s+.*?\s+src=(".*?").*?<\/iframe>

这个替换:

<a href=$1>Link to youtube</a>

它为您提供了以下preg_replace()

$res = preg_replace('/<iframe\s+.*?\s+src=(".*?").*?<\/iframe>/', '/<a href=$1>Link to youtube</a>/', $str);

Live Demo on Regex101

RegEx捕获src之前和之后的所有数据,然后也被替换。

工作原理:

<iframe          # Opening <iframe
\s+              # Whitespace
.*?              # Optional Data (Lazy so as not to capture the src)
\s+              # Whitespace
src=             # src Attribute
    (".*?")          # src Data (i.e. "https://www.example.org")
.*?              # Optional Data (Lazy so as not to capture the closing </iframe>)
<\/iframe>       # Closing </iframe>

感谢@AlexBor告诉我以下内容如果稍微有效率的话。我建议改用RegEx:

<iframe\s+.*?\s+src=("[^"]+").*?<\/iframe>

src=(".*?")替换src=("[^"]+")(懒惰)(贪婪)

答案 1 :(得分:1)

使用像DOMDocument这样的DOM解析器不会让您失望。与正则表达式不同,它是HTML“感知”的。我将在我的loadHTML()调用中添加一些标志,以清除一些额外的html标签生成,对<iframe>标签的所有实例进行迭代,为每个实例创建一个新的<a>元素,并用所需的值,然后用新的<iframe>标签替换<a>标签。

代码:(Demo

$html = <<<HTML
<p><iframe allowfullscreen="" class="media-element file-default" data-fid="2219" data-media-element="1" frameborder="0" height="360" src="https://www.youtube.com/embed/sNEJOm4hSaw?feature=oembed" width="640"></iframe></p>
HTML;

$dom = new DOMDocument;
$dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
foreach ($dom->getElementsByTagName('iframe') as $iframe) {
    $a = $dom->createElement('a');
    $a->setAttribute('href', $iframe->getAttribute('src'));
    $a->nodeValue = "Link to youtube";
    $iframe->parentNode->replaceChild($a, $iframe);
}
echo $dom->saveHTML();

输出:

<p><a href="https://www.youtube.com/embed/sNEJOm4hSaw?feature=oembed">Link to youtube</a></p>

答案 2 :(得分:-1)

最简单的方法是使用preg_match()取出src属性,然后使用它创建a元素。

示例:

$string = "<p><iframe allowfullscreen=\"\" class=\"media-element file-default\" data-fid=\"2219\" data-media-element=\"1\" frameborder=\"0\" height=\"360\" src=\"https://www.youtube.com/embed/sNEJOm4hSaw?feature=oembed\" width=\"640\"></iframe></p>\n";

if( preg_match( '#src=\\"([^ ]*)\\"#', $string, $matches ) === 1 ){
    $string = '<a href="' . $matches[ 1 ] . '">Link to youtube</a>';
    echo $string;
}

// outputs <a href="https://www.youtube.com/embed/sNEJOm4hSaw?feature=oembed">Link to youtube</a>
相关问题