1

多年来我一直试图理解正则表达式,但无济于事!

我有一个系统(假设它是一个清晰的论坛),用户可以在其中发布文本等,他们可以发布 youtube 和 soundcloud 嵌入代码。我正在创建一个过滤器来清理提交的内容(以及使用 htmlpurifier)。因为我们的网站是 SSL,所以我想将嵌入代码格式化为 https:// 并更改 iframe 的大小等。所以我想做的是捕获所有 youtube 和 soundcloud iframe,将它们变成一个标签,例如"%youtube_embed%=dhusydg",运行我的过滤器杀死所有 iframe 等,然后根据我的格式构建 youtube/soundcloud iframe 嵌入。

所以这就是我所拥有的......那不起作用!

$string = preg_replace('/<iframe width="420" height="315" src="http\:\/\/www.youtube.com\/embed\/(.*)" frameborder="0" allowfullscreen>\<\/iframe>/', '%youtube_embed%=$1', $string);

应该做的是找到任何标准的 youtube 嵌入代码,从 url 中提取视频 ID,并将其转换为以后可以替换的字符串。然而,令人沮丧的无法理解正则表达式导致什么也没有发生!我该怎么做?

4

2 回答 2

1
<?php
$string = '<iframe allowfullscreen frameborder="0" height="315"
src="youtube.com/embed/xxxx"; width="420"></iframe>
text
<iframe allowfullscreen frameborder="0" height="315" src="youtube.com/embed/xxxx"; width="420"></iframe> text';
$string = preg_replace(
'/<iframe.*?src="youtube.com\/embed\/(.*?)".*?<\/iframe>/si',
'%youtube_embed%=$1', $string);
print $string;

印刷:

%youtube_embed%=xxxx
text
%youtube_embed%=xxxx text

我对正则表达式使用了 s 和 i 修饰符来忽略换行符并使搜索不区分大小写:

http://www.php.net/manual/en/reference.pcre.pattern.modifiers.php

于 2013-06-10T22:11:57.913 回答
0

感谢 user4035 的帮助,这让我朝着正确的方向前进。完成的代码是这样的;

    $string = '<iframe width="420" height="315" src="http://www.youtube.com/embed/xxxxxx"></iframe>';

    // immunize youtube iframe from filter
    $clean = preg_replace('/<iframe.*?src="http:\/\/www\.youtube\.com\/embed\/(.*)".*?\/iframe>/si','%youtube_embed%=$1',  html_entity_decode($string));
    // apply filtering here e.g removing non youtube iframes etc.

    // create youtube iframe to our own format e.g add class, convert to ssl and change player size etc
    $clean = preg_replace('/%youtube_embed%=(.*)/si','<iframe class="youtube" width="300" height="250" scrolling="no" frameborder="no" src="https://youtube.com/embed/$1"></iframe>',  $clean);
    echo $clean;

注:“?” 在通配符(.*?)中打破了一切,所以我改为(.*).

编辑这仍然不起作用。它破坏了 html 并阻止了替换后的内容。

于 2013-06-11T01:22:27.357 回答