简体   繁体   English

指尖替换包含方括号的字符串

[英]preg replace string containing square brackets

I have a string like this: [name-123456] . 我有一个像这样的字符串: [name-123456]

I am attempting to replace the match of this string with some predefined strings. 我正在尝试用一些预定义的字符串替换此字符串的匹配项。 Here is what I have so far: 这是我到目前为止的内容:

preg_replace('~\['.$string_to_be_replaced.'\]~', $code_to_replace_it_with, $content);

Currently this throws an error, I couldn't find out how to remove the square brackets (even though they are part of the string). 目前,这会引发错误,我无法找出如何删除方括号(即使它们是字符串的一部分)。 How do I make sure those get removed in a regex so that [name-123456] gets replaced with stringofcode ? 我如何确保将它们在正则表达式中删除,以便[name-123456]被替换为stringofcode

EDIT: 编辑:

$string_to_be_replaced = preg_quote($string_to_be_replaced, "~"); 
$content = preg_replace('~\['.$string_to_be_replaced.'\]~', $str_to_replace_with, $content);

this simply returns [name-123456] :p 这只是返回[name-123456]:p

A vardump produces: string(16) "\\[name\\-123456\\]" 一个vardump产生: string(16) "\\[name\\-123456\\]"

Your first problem is likely that you didn't assign the result back: 您的第一个问题可能是您没有将结果分配回去:

$content = preg_replace('~...~', $rpl.., $content);

Then you should also escape the $string_to_be_replaced using preg_quote beforehand. 然后,您还应该使用preg_quote预先转义$string_to_be_replaced It's necessary for the - in your search string anyway. 无论如何,在搜索字符串中都必须有-

$string_to_be_replaced = preg_quote($string_to_be_replaced, "~");

Would also take care of the [ square ] brackets, btw. 还要注意[方括号]

And if you're not doing any assertions or complex matching, str_replace() might be an alternative. 而且,如果您没有进行任何声明或复杂的匹配,则可以使用str_replace()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM