为什么这个PHP字符串不能正确转义?

This works:

$command = "convert C:\wamp\www\site\uploads\a.jpg -resize 40x30 ^ C:\wamp\www\site\uploads\a-thumb.jpg";

exec($command);

Since I am using double quotes I thought this would work too:

    $command = "convert C:\wamp\www\site\uploads\$file_name.jpg -resize 40x30 ^ C:\wamp\www\site\uploads\$file_name-thumb.jpg";

    exec($command);

but the $file_name var isn't being recorgnized as such but it seen as a string for some reason.

So I tried this:

$command = "convert C:\wamp\www\site\uploads\".$file_name.".jpg -resize 40x30 ^ C:\wamp\www\site\uploads\".$file_name."-thumb.jpg";

exec($command);

But this throws a bunch of syntax errors.

How to escape this string properly? By escape I just mean how can I use this with the variable $file_name.

Try the following to rules:

$command = "convert C:\wamp\www\site\uploads\{$file_name}.jpg -resize 40x30 ^ C:\wamp\www\site\uploads\{$file_name}-thumb.jpg";
exec($command);

or:

$command = "convert C:\wamp\www\site\uploads\%s.jpg -resize 40x30 ^ C:\wamp\www\site\uploads\%s-thumb.jpg";
exec(sprintf($command, $filename, $filename));

No you should use single quotes for it to escape properly.

You can add brackets to make it work:

$command = "convert C:\wamp\www\site\uploads\{$file_name}.jpg -resize 40x30 ^ C:\wamp\www\site\uploads\{$file_name}-thumb.jpg";