doushan7077 2013-10-25 01:09
浏览 33

在PHP preg_replace的替换参数中转义引用外观相似

I would like to replace a pattern string '/r/' within a subject string 'r r' with predetermined replacements like '"\\23"' and '[4]'. So (showing you only a subset of my replacements array) I try:

$subject = 'r r';
$replacements = array('"\\23"', '[4]');
$replacements = array_map('preg_quote', $replacements);
print_r($replacements);

foreach($replacements as $replacement){
    $subject = preg_replace('/r/', $replacement, $subject, 1);
}

echo $subject;

The string I want is '"\\23" [4]', but I get back '"\23" \[4\]', which is both missing characters and has additional characters.

Does PHP have an escape function that would work here? How do I do this?

Note: Without the preg_quote line the result is '"" [4]'.

  • 写回答

1条回答 默认 最新

  • dpzlz08480 2013-10-25 01:18
    关注

    preg_quote function is needed only for first argument of preg_replace if it should be escaped, so remove it

    to replace r with "\\23" you need to use:

    $subject = 'r r';
    $replacements = array('"\\\\23"', '[4]'); // here is double escaping, but only in code, for input you do no need to escape anyhitng
    foreach ($replacements as $replacement)
        $subject = preg_replace('/r/', addcslashes($replacement, '\\'), $subject, 1); // here is the addition of \ only to \, as it is required by preg_replace
    echo $subject;
    

    http://php.net/manual/en/function.preg-replace.php

    To use backslash in replacement, it must be doubled ("\\\\" PHP string).

    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?