php - 将 iframe 替换为带有正则表达式的链接

标签 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 中的 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);

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=("[^"]+")(贪婪)

关于php - 将 iframe 替换为带有正则表达式的链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36421411/

相关文章:

java - 如何使用正则表达式查找字符串中子字符串的不同出现次数?

python - 是否有与正则表达式的 Perl "/x"修饰符等效的 Python?

javascript - 用于捕获最后一组括号的 JS 正则表达式(不包括嵌套)

php - 仅针对具有处理状态的付费订单发送 WooCommerce 新订单电子邮件通知

javascript - PHP联系表单修改

php - 使用 PHP 将 Jquery 可排序值保存到 mysql 数据库

php - 读取大文本文件并将所选行复制到另一个文件

php - php |通过正则表达式在数组中查找

javascript - 如何使用javascript查找并替换字符串中的2个整数

php - 用 PHP 表省区和街道