PHP Regex:选择除最后一次出现之外的所有内容

时间:2011-10-10 21:27:54

标签: php regex preg-replace

我正在尝试用\n替换所有\n\t的最后一个sans,以便很好地缩进递归函数。

This
that
then
thar
these
them

应该成为:

This
    that
    then
    thar
    these
them

这就是我所拥有的:preg_replace('/\n(.+?)\n/','\n\t$1\n',$var);

它目前吐出来了:

This
    that
then
thar
these
them

快速概览:

需要使用正则表达式缩小第一行和最后一行的每一行,我该如何实现?

4 个答案:

答案 0 :(得分:3)

您可以使用lookahead

$var = preg_replace('/\n(?=.*?\n)/', "\n\t", $var);

在此处查看:ideone

答案 1 :(得分:2)

修复报价问题后,您的输出实际就像这样:

This
    that
then
    thar
these
them

使用positive lookahead可以阻止搜索正则表达式使\n落后echo preg_replace('/\n(.+?)(?=\n)/', "\n\t$1", $input); // newline-^ ^-text ^-lookahead ^- replacement 。你的“光标”已经超出了它,所以只有其他每一行都被重写了;你的匹配“区域”重叠。

{{1}}

Live demo.

答案 2 :(得分:1)

preg_replace('/\n(.+?)(?=\n)/',"\n\t$1",$var);

将第二个\n修改为前瞻(?=\n),否则您会遇到正则表达式无法识别重叠匹配的问题。

http://ideone.com/1JHGY

答案 3 :(得分:-1)

让downwoting开始,但为什么要使用正则表达式?

<?php
$e = explode("\n",$oldstr);
$str = $e[count($e) - 1]; 
unset($e[count($e) - 1]);
$str = implode("\n\t",$e)."\n".$str;
echo $str;
?>

实际上,str_replace有一个“count”参数,但我似乎无法让它与php 5.3.0一起使用(发现了一个错误报告)。这应该有效:

<?php
$count = substr_count($oldstr,"\n") - 1;
$newstr = str_replace("\n","\n\t",$oldstr,&$count);
?>
相关问题