Executing multiline sed in php: escaping issues

2019-08-13 10:00发布

I am trying to run sed to do a multiline search and replace with the following string

$test = "sed -n '1h;1!H;${;g;s/iname=\"".$name.".*item>/".trim(xml)."/g;p;}' ".$file;
exec($test,$cmdresult);

sed is choice since the string to be searched is over 10 mb.

During execution compiler issues a warning

PHP Parse error:  syntax error, unexpected ';' 

How do I go about solving this?

2条回答
手持菜刀,她持情操
2楼-- · 2019-08-13 10:15

You need to escape the $ in ${}.

$test = "sed -n '1h;1!H;\${;g;s/iname=\"".$name.".*item>/".trim(xml)."/g;p;}' ".$file;
exec($test,$cmdresult);

In order to let humans read your code, though, you should really split the string up. Create it by concatenating other strings, sprintf or HEREDOC.

查看更多
We Are One
3楼-- · 2019-08-13 10:15

Probably the $ sign inside the $test variable makes PHP think that there is another variable that should be expanded.

Try escaping the $ character (\$), and have a look at the relevant PHP strings doc.

查看更多
登录 后发表回答