正则表达式无效的哈希替换

时间:2018-02-15 15:45:20

标签: php regex

在此文件中,我想将UNDER_CONSTRUCTION_HASH更改为另一个 哈希,我用正则表达式做。

文件:

MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null

PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_APP_CLUSTER=mt1

MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"

UNDER_CONSTRUCTION_HASH=y$TwrFXK90UkJ4pq4grH1/hevPgkdOE4lEmPI9QbhVnwH1UEyYr/zA2

我想将UNDER_CONSTRUCTION_HASH替换为另一个:

$2y$10$TwrFXK90UkJ4pq4grH1/hevPgkdOE4lEmPI9QbhVnwH1UEyYr/zA2

我的代码一起看起来像这样:

$envContent = $this->filesystem->get($envPath);
$regex = '/UNDER_CONSTRUCTION_HASH=[^\s]+/';
$newLine = sprintf('UNDER_CONSTRUCTION_HASH=%s', $hash);

if (preg_match($regex, $envContent)) {
    var_dump($newLine);
    $envContent = preg_replace($regex, $newLine, $envContent);
} else {
    $envContent .= "\n".$newLine."\n";
}

结果如下:

UNDER_CONSTRUCTION_HASH=y$TwrFXK90UkJ4pq4grH1/hevPgkdOE4lEmPI9QbhVnwH1UEyYr/zA2

而不是:

UNDER_CONSTRUCTION_HASH=$2y$10$TwrFXK90UkJ4pq4grH1/hevPgkdOE4lEmPI9QbhVnwH1UEyYr/zA2

这里可能有什么问题?

我的包裹:https://github.com/larsjanssen6/underconstruction

1 个答案:

答案 0 :(得分:2)

这是逃避美元符号的问题。

$hash注入$newLine并用作preg_replace()的替换参数时,该函数假定$2$1是捕获组引用。你需要在它们前面放置斜线才能对它们进行字面处理。

这是重写:

代码:(Demo

$envContent='MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null

PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_APP_CLUSTER=mt1

MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"

UNDER_CONSTRUCTION_HASH=y$TwrFXK90UkJ4pq4grH1/hevPgkdOE4lEmPI9QbhVnwH1UEyYr/zA2';

$hash = '$2y$10$TwrFXK90UkJ4pq4grH1/hevPgkdOE4lEmPI9QbhVnwH1UEyYr/zA2';
$pattern = '/UNDER_CONSTRUCTION_HASH=\S+/';
$replace = "UNDER_CONSTRUCTION_HASH=".str_replace('$','\$',$hash);  // <-- escape your dollar signs
$newLine = "UNDER_CONSTRUCTION_HASH=$hash";

$envContent = preg_replace($pattern, $replace, $envContent, -1, $count);
if(!$count){
    //echo "no replacement made\n";
    $envContent .= "\n".$newLine."\n";
}

echo $envContent;

输出:

MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null

PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_APP_CLUSTER=mt1

MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"

UNDER_CONSTRUCTION_HASH=$2y$10$TwrFXK90UkJ4pq4grH1/hevPgkdOE4lEmPI9QbhVnwH1UEyYr/zA2