我目前有这个字符串:
"<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
中的 url属性:
<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
元素。
实现此目标的最简单方法是什么?
最佳答案
使用这个正则表达式:
<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);
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=("[^"]+")
(贪婪)
关于php - 将 iframe 替换为带有正则表达式的链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36421411/