【问题标题】:Escape brackets within string字符串中的转义括号
【发布时间】:2016-03-15 22:02:08
【问题描述】:

我需要在文件名中转义括号。目前我这样做如下:

$string = 'folder1/folder2/foldera/abc/myFile(2).jpg';

str_replace(')', '\)', str_replace('(', '\(', $string));

echo $string;

// outputs: folder1/folder2/foldera/abc/myFile\(2\).jpg 

这是低效的,因为这是在数百个结果的循环中执行的。有没有更好、更清洁、更有效的方法来实现这一目标?

【问题讨论】:

  • 可能是preg_quote()?
  • 只是出于好奇,为什么要转义圆括号??
  • @Andrew 这是因为我在数据馈送中输出此内容,而收件人要求以这种方式转义括号。

标签: php regex str-replace


【解决方案1】:

您可以通过使用数组来减少对str_replace() 的调用。

str_replace(array(')', '('),  array('\)', '\('), $string);

附言: 另一个选项是preg_quote(),但在您的情况下,您只想转义()。而preg_quote() 将转义所有regex 字符。

【讨论】:

  • 正如@jiboulex 所说,[] 现在等同于array()
【解决方案2】:

我认为您正在寻找 preg_quote :

$string = preg_quote($string);

或者类似的东西:

$string = str_replace([')', '('], ['\\)', '\\('], $string);

【讨论】:

【解决方案3】:

试试这个

$findstring = array('(',')');
$escpestring = array('\(','\)');
$string = 'folder1/folder2/foldera/abc/myFile(2).jpg';
$output = str_replace($findstring,$escpestring,$string);
echo $output;

【讨论】:

    【解决方案4】:

    不知有没有更好的函数是escapeshellcmd(http://php.net/manual/en/function.escapeshellcmd.php)

    后面的字符以反斜杠开头:`|*?~^()[]{}$\、\x0A 和 \xFF。 ' 和 " 仅在它们未配对时才被转义。在 Windows 中,所有这些字符加上 % 和 ! 都被替换为空格。

    【讨论】:

      猜你喜欢
      • 2016-01-13
      • 2011-08-09
      • 1970-01-01
      • 2014-01-24
      • 2010-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多