我目前有这个字符串:
"<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>"
Run Code Online (Sandbox Code Playgroud)
我想删除整个iframe元素(<iframe>...</iframe>),并用<a>指向该src属性中url 的链接替换它:
<p><a href="https://www.youtube.com/embed/sNEJOm4hSaw?feature=oembed">Link to youtube</a></p>
Run Code Online (Sandbox Code Playgroud)
目前,我有这个正则表达式:
$res = preg_replace('/src="(.+?)"/', '/<a href="$1">Link to youtube</a>/', $str);
Run Code Online (Sandbox Code Playgroud)
使用此正则表达式,我可以src用一个a元素替换该属性。但是,我想替换整个iframe元素。
最简单的方法是什么?
使用此RegEx:
<iframe\s+.*?\s+src=(".*?").*?<\/iframe>
Run Code Online (Sandbox Code Playgroud)
并替换:
<a href=$1>Link to youtube</a>
Run Code Online (Sandbox Code Playgroud)
这给您以下内容preg_replace():
$res = preg_replace('/<iframe\s+.*?\s+src=(".*?").*?<\/iframe>/', '/<a href=$1>Link to youtube</a>/', $str);
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
感谢@AlexBor通知我以下操作效率更高。我建议改用此RegEx:
<iframe\s+.*?\s+src=("[^"]+").*?<\/iframe>
Run Code Online (Sandbox Code Playgroud)
src=(".*?")用src=("[^"]+")(贪婪)取代(懒惰)