PHP字符串:如何替换非标准字符?
当字符串的一部分和替换内容都包含特殊字符时,如何替换该部分?例如
$text = "|123|12|12|";
$text = preg_replace("|0|","|12|",$text, 1);
echo($text);
所需的输出:“|123|0|12|”
只要保留特殊字符就无关紧要。例如
$text = "#123#12#12#";
$text = preg_replace("#0#","#12#",$text, 1);
echo($text);
所需的输出:“#123#0#12#”
有什么想法吗?
How can I replace part of a string, when that part and the replacement both include special characters? e.g.
$text = "|123|12|12|";
$text = preg_replace("|0|","|12|",$text, 1);
echo($text);
Desired output: "|123|0|12|"
The special characters don't matter as long as they are preserved. E.g.
$text = "#123#12#12#";
$text = preg_replace("#0#","#12#",$text, 1);
echo($text);
Desired output: "#123#0#12#"
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你的图案需要擒纵机构,因为“|”是reg规则中的特殊字符。
使用“\”转义字符,然后使用“/”作为模式的分隔符。
试试这个。 :)
编辑:
BTY,我猜你想替换第一个“|12|”与'|0|',但你的代码让我感到困惑。
函数preg_replace的语句如下:
也许您将参数放在了错误的位置。
有关 preg_replace 的更多信息,请参阅: http://cn.php.net/manual/ en/function.preg-replace.php
Your pattern needs escapement,because the '|' is a special char in reg rules.
Use '\' to escape your char, and then use '/' as the delimiter of your pattern.
Try this. :)
EDIT:
BTY, I guess you want to replace the first '|12|' with '|0|', but your code makes me puzzled.
The function preg_replace's statement is as below:
Maybe you had put the parameters in wrong places.
See more about preg_replace: http://cn.php.net/manual/en/function.preg-replace.php
如果不需要正则表达式,请使用
str_replace
而不是preg_replace
。它更有效并且避免了逃避任何事情的需要。如果您需要使用
preg_replace
(例如,利用可以指定替换数量限制的优势,与str_replace
不同),请使用preg_quote
转义特殊字符。Use
str_replace
instead ofpreg_replace
if you don't need regexp. It's more efficient and avoids the need to escape anything.If you need to use
preg_replace
(for instance to take advantage of the fact that you can specify a limit for the number of replacements, unlike withstr_replace
), usepreg_quote
to escape the special characters.| 的 |充当正则表达式开始的标记。你真的很接近:
这里我使用 / 作为开始和结束标记。您可以使用任何字符。 / 很常见。
请注意,str_replace 在这里也足够了
The | acts as the marker for the start of the regex. You're quite close really:
Here I used / as the start and end-markers. You can use any character. / is quite common.
Note that str_replace would also suffice here