双引号继续在PHP的shell_exec和sed中解析

I've spent hours trying to figure this out. I am using shell_exec (yes, I know the security problems associated with this) and sed to change text in a file.

The problem is no matter what I try I can't seem to output the text with the quotes still intact. I've tried almost every combination of single and double quotes I could to escape it, but it hasn't worked. After hours of trying, I decided to ask the question here.

The code is in a PHP file:

shell_exec('sed -i "s/patterntoreplace/yolo(word,"Hello Everyone", word)/" test.txt

The problem is that the file ends up with:

yolo(word,Hello Everyone, word)

The quotes keep getting parsed and I absolutely need them. I tried various things such as putting it into a variable, using escapeshellarg and escapeshellcmd and trying various combinations of single and double quotes, but I still can't get it to work.

This is very frustrating for me because this is the last part of my project and it should be simple, yet I can't run my program without the quotes. It's rather infuriating.

Can someone please tell me what to replace in that command to get quotes to output correctly?

have you tried to use \' instead of ' and \" instead of " where you dont wnat them to be parsed? They said that already! :)

This should work:

$arg = 's/patterntoreplace/yolo(word,"Hello Everyone", word)/';
$cmd = 'sed -i '.escapeshellarg($arg).' test.txt';
shell_exec($cmd);

This can and should be done with PHP, no sed required:

$filename = 'test.txt';
$pattern = 'patterntoreplace';
$replace = 'yolo(word,"Hello Everyone", word)';

$lines = []; 
foreach(file($filename) as $line) {
    $lines []= preg_replace($pattern, $replace, $line);
}

file_put_contents($filename, join("", $lines));