【发布时间】:2013-04-19 06:52:06
【问题描述】:
我在 PHP 中遇到了替换字符串中的 (ss) 的问题。
$string = 'I want a new (ss) now!';
$newString = preg_replace('\(ss\)', 'car', $string);
我期待 $newString 变成:
我现在想要一辆新车!
我在这里做错了什么?
【问题讨论】:
标签: php regex preg-replace
我在 PHP 中遇到了替换字符串中的 (ss) 的问题。
$string = 'I want a new (ss) now!';
$newString = preg_replace('\(ss\)', 'car', $string);
我期待 $newString 变成:
我现在想要一辆新车!
我在这里做错了什么?
【问题讨论】:
标签: php regex preg-replace
您的问题是您的正则表达式没有delimiters。
但是,鉴于您没有使用任何正则表达式功能,您最好使用str_replace()。
【讨论】:
使用str_replace
$string = 'I want a new (ss) now!';
$newString = str_replace('(ss)', 'car', $string);
输出
我现在想要一辆新车!
以preg_replace 为例
$string = 'I want a new (ss) now!';
$newString = preg_replace('$\(ss\)$', 'car', $string);
输出
我现在想要一辆新车!
【讨论】:
$newString = str_replace("ss", "car", $string);
【讨论】:
使用 str_replace()
$newString = str_replace("(ss)", "car", $string);
【讨论】: