dorv56831 2011-03-05 22:47
浏览 108
已采纳

preg_replace中替换数组中的特殊(转义)字符会被转义

I’m trying to modify a string of the following form where each field is delimited by a tab except for the first which is followed by two or more tabs.

"$str1      $str2   $str3   $str4   $str5   $str6"

The modified string will have each field wrapped in HTML table tags, and be on its own, indented line as so.

"<tr>
  <td class="title">$str1</td>
  <td sorttable_customkey="$str2"></td>
  <td sorttable_customkey="$str3"></td>
  <td sorttable_customkey="$str4"></td>
  <td sorttable_customkey="$str5"></td>
  <td sorttable_customkey="$str6"></td>
</tr>

"

I tried using code like the following to do it.

$patterns = array();
$patterns[0]='/^/';
$patterns[1]='/\t\t+/';
$patterns[2]='/\t/';
$patterns[3]='/$/';

$replacements = array();
$replacements[0]='\t\t<tr>
\t\t\t<td class="title">';
$replacements[1]='</td>
\t\t\t<td sorttable_customkey="';
$replacements[2]='"></td>
\t\t\t<td sorttable_customkey="';
$replacements[3]='"></td>
\t\t</tr>
';

for ($i=0; $i<count($lines); $i++) {
  $lines[$i] = preg_replace($patterns, $replacements, $lines[$i]);
}

The problem is that the escaped characters (tabs and newlines) in the replacement array remain escaped in the destination string and I get the following string.

"\t\t<tr>
\t\t\t<td class="title">$str</td>
\t\t\t<td sorttable_customkey="$str2"></td>
\t\t\t<td sorttable_customkey="$str3"></td>
\t\t\t<td sorttable_customkey="$str4"></td>
\t\t\t<td sorttable_customkey="$str5"></td>
\t\t\t<td sorttable_customkey="$str6"></td>
\t\t</tr>
"

Strangely, this line I tried earlier on does work:

$data=preg_replace("/\t+/", "\t", $data);

Am I missing something? Any idea how to fix it?

  • 写回答

2条回答 默认 最新

  • doudou_3636 2011-03-05 22:51
    关注

    You need double quotes or heredocs for the replacement string - PCRE only parses those escape characters in the search string.

    In your working example preg_replace("/\t+/", "\t", $data) those are both literal tab characters because they're in double quotes.

    If you changed it to preg_replace('/\t+/', '\t', $data) you can observe your main problem - PCRE understands that the \t in the search string represents a tab, but doesn't for the one in the replacement string.

    So by using double quotes for the replacement, e.g. preg_replace('/\t+/', "\t", $data), you let PHP parse the \t and you get the expected result.

    It is slightly incongruous, just something to remember.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历