2011-02-16 114 views
0

我想要采取一个随机字符串并在preg_replace中使用它。当$ random接受一个包含[字符php返回“编译失败:缺少终止”的字符类的偏移量为“错误”的值时。不只是]还有其他角色会导致错误。搜索包含字符的字符串问题[preg_replace

我该如何解决这个问题?

$random='asd[qwe'; 

preg_replace("/$random/", "replaced value", $text, 1); 

任何想法?

回答

1

某些字符需要转义。您可以设置一系列需要转义或逃避的字符:

$random='asd\[qwe'; 

preg_replace("/$random/", "replaced value", $text, 1); 

应该有效。 这里是一个数组做的一个例子:

$random='asd[qwe('; 

$escape = array('[', ']', ')', '('); 
foreach ($escape as $esc) { 
    $random = str_replace($esc, '\\' . $esc, $random); 
} 

preg_replace("/$random/", "replaced value", $text, 1); 

我肯定可以美化了一番,但高雅。

删除为preg_quote肯定是更好的方法。

3

你必须逃避它。你可以用preg_quote

$random = preg_quote('asd[qwe', '/'); 
preg_replace("/$random/", "replaced value", $text, 1); 
+0

不错,你每天都会学到新的东西! +1。 – 2011-02-16 20:30:17

相关问题