我目前有这个字符串:
"<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>
(,并将其替换为指向 src
属性中 url 的<a>
链接:
<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
元素。
实现这一目标的最简单方法是什么?
使用此正则表达式:
<iframes+.*?s+src=(".*?").*?</iframe>
而这个替换:
<a href=$1>Link to youtube</a>
这为您提供以下preg_replace()
:
$res = preg_replace('/<iframes+.*?s+src=(".*?").*?</iframe>/', '/<a href=$1>Link to youtube</a>/', $str);
正则表达式101上的现场演示
正则表达式捕获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告诉我,以下内容的效率略高。我建议改用这个正则表达式:
<iframes+.*?s+src=("[^"]+").*?</iframe>
将src=(".*?")
(懒惰(替换为src=("[^"]+")
(贪婪(
使用像 DOMDocument 这样的 DOM 解析器不会让你失望。 与正则表达式不同,它是 HTML"感知"的。 我将在我的loadHTML()
调用中添加一些标志,以清除一些额外的 html 标签生成,迭代所有出现的<iframe>
标签,为每个出现创建一个新的 <a>
元素,用所需的值填充它,然后将<iframe>
标签替换为新的 <a>
标签。
代码:(演示(
$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>
最简单的方法是使用 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>