替换给定字符串和换行符之间的字符串

时间:2017-04-25 01:42:50

标签: php regex pcre

我的文件只包含一次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';

2 个答案:

答案 0 :(得分:1)

这里我使用正则表达式进行搜索和替换,

正则表达式 /(search_for_me).*?\n/,这将与search_for_me匹配,直到\n

替换'\1=21.12/44.22/44'."\n"此处\1将包含首先捕获的群组search_for_me

Try this code snippet here

<?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