我的文件只包含一次search_for_me=12.21/13.31/14
后跟line break
。我希望将12.21/13.31/14
替换为21.12/44.22/44
。如何实现这一目标?
<?php
/*
$string = 'April 15, 2003';
$pattern = '/(\w+) (\d+), (\d+)/i';
$replacement = '${1}1,$3';
echo preg_replace($pattern, $replacement, $string)."\n\n\n";
//April1,2003
*/
$string = file_get_contents('test.conf');
$string= <<<EOT
bla bla bla
search_for_me=12.21/13.31/14
bla bla bla
EOT;
echo $string."\n\n";
$replace = "21.12/44.22/44";
$search = "/[^search_for_me=](.*)[^\n]/";
echo preg_replace($search,$replace,$string)."\n\n";
echo 'done';
答案 0 :(得分:1)
这里我使用正则表达式进行搜索和替换,
正则表达式 /(search_for_me).*?\n/
,这将与search_for_me
匹配,直到\n
替换:'\1=21.12/44.22/44'."\n"
此处\1
将包含首先捕获的群组search_for_me
。
<?php
/*
$string = 'April 15, 2003';
$pattern = '/(\w+) (\d+), (\d+)/i';
$replacement = '${1}1,$3';
echo preg_replace($pattern, $replacement, $string)."\n\n\n";
//April1,2003
*/
$string = file_get_contents('test.conf');
$string= <<<EOT
bla bla bla
search_for_me=12.21/13.31/14
bla bla bla
EOT;
echo $string."\n\n";
$replace = "21.12/44.22/44";
$search = "/(search_for_me)=.*?\n/";
echo preg_replace($search,'\1=21.12/44.22/44'."\n",$string)."\n\n";
答案 1 :(得分:1)
试试这个:
$string= <<<EOT
bla bla bla
search_for_me=12.21/13.31/14
bla bla bla
EOT;
printf("-String without replace:\n\n%s\n\n", $string);
$replace = '21.12/44.22/44';
$pattern = '/(?<=search_for_me\=)(.*)/';
$new_string = preg_replace($pattern, $replace, $string);
printf("-String with replace:\n\n%s", $new_string);
我使用积极的lookbehind HERE