替换从行首到等号的所有内容

时间:2011-07-01 13:08:44

标签: php regex

对于格式为

的内容
KEY=VALUE

像:

LISTEN=I am listening.

我需要使用正则表达式进行替换。我希望这个正则表达式在= $键之前替换任何东西(使它必须从行的开头,所以像'EN'这样的键不会替换像“TOKEN”这样的键。

这是我正在使用的,但它似乎不起作用:

$content = preg_replace('~^'.$key.'\s?=[^\n$]+~iu',$newKey,$content);

5 个答案:

答案 0 :(得分:1)

$str = 'LISTEN=I am listening.';
$new_key = 'ÉCOUTER';

echo preg_replace('/^[^=]*=/', $new_key . '=', $str);

答案 1 :(得分:1)

$content = "foo=one\n"
         . "bar=two\n"
         . "baz=three\n";

$keys = array(
    'foo' => 'newFoo',
    'bar' => 'newBar',
    'baz' => 'newBaz',
);
foreach ( $keys as $oldKey => $newKey ) {
    $oldKey = preg_quote($oldKey, '#');
    $content = preg_replace("#^{$oldKey}( ?=)#m", "{$newKey}\\1", $content);
}

echo $content;

输出:

newFoo=one
newBar=two
newBaz=three

答案 2 :(得分:1)

如果我理解你的问题,你需要使用m修饰符切换多行模式。

$content = preg_replace('/^'.preg_quote($key, '/').'(?=\s?=)/ium', $newKey, $content);

顺便提一下,我建议使用$key来逃避preg_quote以避免意外结果。

因此,如果源内容是这样的:

KEY1=VALUE1
HELLO=WORLD
KEY3=VALUE3

结果将是(如果$key=HELLO$newKey=BYE):

KEY1=VALUE1
BYE=WORLD
KEY3=VALUE3

答案 3 :(得分:0)

$content = 'LISTEN=I am listening.';
$key = 'LISTEN';
$newKey = 'NEW';


$content = preg_replace('~^'.$key.'(\s?=)~iu',$newKey.'$1',$content);

echo $content;

输出为NEW=I am listening.

但是部分匹配不会改变

$content = 'LISTEN=I am listening.';
$key = 'TEN';
$new_key = 'NEW';

$content = preg_replace('~^'.$key.'(\s?=)~iu',$newKey.'$1',$content);

echo $content;

输出为LISTEN=I am listening.

答案 4 :(得分:0)

这应该可以解决问题。 \ A是一行的开头,括号用于分组要保留/替换的东西。

$new_content = preg_replace("/\A(.*)(=.*)/", "$key$2", $content);