Preg_replace不转义"?"在引用


preg_replace not escaping "?" within references

我有一个字符串,有很多文本,bbcodes和url,我从bbcode- youtube - URLs提取id,然后用嵌入的youtube iframe替换bbcode。到目前为止一切顺利,这是有效的。

但是对于我的网站,我需要添加"?wmode=opaque"到iframe src="//www.youtube.com/embed/$1"属性,但"?"不能使用preg_replace.

这是基本代码:
function youtube_bbcode_format($str){
   // extract id
   $format_search =  array(
      '#'[youtube'].*[?&]v=([^?&]+)'[/youtube']#i' // Youtube extract id
   );
   // replace string (youtube embed iframe) plus the ?wmode=opaque parameter
   $format_replace = array(
      '<iframe width="320" height="180" src="//www.youtube.com/embed/$1?wmode=opaque" frameborder="0" allowfullscreen></iframe>'
   );
   // do the replacement
   $str = preg_replace($format_search, $format_replace, $str);
   return $str;
}

我试过用各种方法转义/embed/$1旁边的"?"问号,下面的例子不起作用:($1在所有示例中都被正确地替换为youtube id,我只是没有每次都写下来)

src="//www.youtube.com/embed/$1?wmode=opaque"

在浏览器中$1之后的所有内容都丢失了,包括"?"结果:/$1

src="//www.youtube.com/embed/$1'?wmode=opaque" 

转义不能正常工作。结果:'/1美元吗?Wmode =opaque(反斜杠应该去掉!)

src="//www.youtube.com/embed/$1''?wmode=opaque"

与之前相同,result:/$1'?不透明窗口模式=

src="//www.youtube.com/embed/$1??wmode=opaque" 

结果:/$ 1 ? ?不透明窗口模式=

src="//www.youtube.com/embed/'${1}?wmode=opaque"

结果:/$ {1}?不透明窗口模式=

最后一次尝试是最有希望的,因为在手册中说这是处理这类问题的方法,但它不起作用。

如何逃避"?"在replace-string?

PS:输入字符串的示例:

    str = "music is by [color=blue][size=20][b]Pegboard Nerds - Hero (feat. Elizaveta)[/b][/size][/color]. you can listen to it here:[br][youtube]youtube.com/watch?v=5lLclBfKj48[/youtube]";

(其他bbcode标签在别处处理)

试试这个:

function youtube_bbcode_format($str){
   // extract id
   $format_search =  array(
      '#'[youtube'].*[?&]v=([^?&]+)'[/youtube']#i' // Youtube extract id
   );
   // replace string (youtube embed iframe) plus the ?wmode=opaque parameter
   $format_replace = array(
      '<iframe width="320" height="180" src="//www.youtube.com/embed/$1'
   );
   // do the replacement
   $str = preg_replace($format_search, $format_replace, $str).'?wmode=opaque" frameborder="0" allowfullscreen></iframe>';
   return $str;
}

感谢大家验证代码示例。你是对的,代码片段本身像预期的那样工作。我确信问题在preg_replace引用中,但是我错了。问题的根源来自我的源代码中的另一部分:$str通过另一个preg_replace函数传递,该函数将问号删除。

    preg_replace_callback("&''b$rexProtocol$rexDomain$rexPort$rexPath$rexQuery$rexFragment(?=[?.!,;:'"]?('s|$))&", 'callback', $str);

preg_replace_callback函数应该用真实链接替换文本链接。但是如果在我的基本代码剪切之后调用它,"?"后面的所有内容(包括它自己)不见了。

代码段本身确实可以工作。谢谢你的帮助。