This function is great -- except when you need to legitimately use an escaped character as part of your command. The code below leaves the parts of the command that are enclosed within single quotes alone, but escapes the rest eg:
"echo Never use the '<blink>' tag ; cat /etc/passwd"
becomes:
"echo Never use the '<blink>' tag \; cat /etc/passwd"
and not:
"echo Never use the '\<blink\>' tag \; cat /etc/passwd"
i.e, we really want the ';' escaped, but not the HTML tag. I really needed the code below in order to run the external ImageMagick's 'convert' command properly and safely...
<?php
$cmdQ = escapeshellcmd($cmd);
preg_match_all('/\'[^\']+\'/', $cmd, $matches);
$matches = current($matches);
$quoted = array();
foreach( $matches as $match )
$quoted[escapeshellcmd($match)] = $match;
foreach( $quoted as $search => $replace )
$cmdQ = str_replace( $search, $replace, $cmdQ );
return $cmdQ;
?>