我正在尝试用一些短代码替换所有的soundcloud iframe。我还使用preg_replace创建了一个脚本,但这只适用于第一次出现的iframe,还有一些我无法弄清楚的问题。
这是我的字符串
$con = '<iframe src="http://w.soundcloud.com/player/?url=http%3A%2F%2Fapi.soundcloud.com%2Ftracks%2F59701079&auto_play=false&show_artwork=true&color=00adee" frameborder="no" scrolling="no" width="100%" height="166"></iframe>came over from Berlin for a couple of days. Mad fun that guy is!! We actually made 2 tracks during his stay here. The other one will be released soon.<iframe src="http://www.youtube.com/embed/z3fIsvQDrqI" frameborder="0" width="460" height="259"></iframe>\r\n<strong><span style="color: #3366ff;">GDD:</span></strong> So wild! Well were very happy youre getting the deserved attention! Tell us what you have coming up next in the Kill Frenzy world!\r\n<span style="color: #ff0000;"><strong>KF:</strong></span><iframe src="http://w.soundcloud.com/player/?url=http%3A%2F%2Fapi.soundcloud.com%2Ftracks%2F53146049&auto_play=false&show_artwork=true&color=00adee" frameborder="no" scrolling="no" width="100%" height="166"></iframe>'
;
基本上我要做的是转换
<iframe src="http://w.soundcloud.com/player/?url=http%3A%2F%2Fapi.soundcloud.com%2Ftracks%2F59701079&auto_play=false&show_artwork=true&color=00adee" frameborder="no" scrolling="no" width="100%" height="166"></iframe>
到
[soundcloud url="http://api.soundcloud.com/tracks/59701079"]
对于所有出现的irame但问题是当我运行此脚本时
$new_con = preg_replace('/(?:<iframe[^\>]+src="[^\"]*url=([^\"]*soundcloud\.com[^\"]*))"[^\/]*\/[^\>]*>/i', '[soundcloud url="$1"]', $con);
$ new_con返回类似这样的内容
[soundcloud url="http%3A%2F%2Fapi.soundcloud.com%2Ftracks%2F59701079&auto_play=false&show_artwork=true&color=00adee"]came over from Berlin for a couple of days. Mad fun that guy is!! We actually made 2 tracks during his stay here. The other one will be released soon.<iframe src="http://www.youtube.com/embed/z3fIsvQDrqI" frameborder="0" width="460" height="259"></iframe>\r\n<strong><span style="color: #3366ff;">GDD:</span></strong> So wild! Well were very happy youre getting the deserved attention! Tell us what you have coming up next in the Kill Frenzy world!\r\n<span style="color: #ff0000;"><strong>KF:</strong></span>[soundcloud url="http%3A%2F%2Fapi.soundcloud.com%2Ftracks%2F53146049&auto_play=false&show_artwork=true&color=00adee"]
有人可以指导我这样做吗?
答案 0 :(得分:0)
使用第四个参数:
$new = preg_replace('/regex/', $replace, $string, 1);
// here ___^
它只会替换第一次出现的正则表达式。
更多信息here
答案 1 :(得分:0)
我终于可以使用以下
来解决这个问题$new_con = preg_replace_callback('/(?:<iframe[^\>]+src="[^\"]*url=([^\"]*soundcloud\.com[^\"]*))"[^\/]*\/[^\>]*>/i', function($match) {
$string = explode("&",$match[1]);
return '[soundcloud url="'.urldecode($string[0]).'"]';
}, $con);