按原样创建包含混合引号的字符串变量

How can I take a string with lots of mixed double and single quotes:

curl -A 'Curl/2.5' -d '{"key":"$api_key","message":{"html":"<p><h1>Hello World</h1><\/p>"}'

and create a string variable such as:

$curl_command = "curl -A 'Curl/2.5' -d '{"key":"$api_key","message":{"html":"<p><h1>Hello World</h1><\/p>"}'"

Without returning "unexpected ' errors"? I want to avoid changing the original string.

You can use heredoc syntax and escape all the quotes and double quotes easily.

Here is the syntax for it. http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc

Take care not leave space before the heredoc identifier.

Make use of HEREDOC Syntax.

<?php
$api_key='xx2233';
$content=<<<EOD
curl -A 'Curl/2.5' -d '{"key":"$api_key","message":{"html":"<p><h1>Hello World</h1><\/p>"}'
EOD;

echo $curlCommand=$content;

OUTPUT :

curl -A 'Curl/2.5' -d '{"key":"xx2233","message":{"html":" Hello World

</p>"}

You can use Heredoc:

$string = <<<someStringYouWillAlsoNeedToStop
curl -A 'Curl/2.5' -d '{"key":"$api_key","message":{"html":"<p><h1>Hello World</h1><\/p>"}'
someStringYouWillAlsoNeedToStop; // this ends your string

Beware that heredoc DOES parse your $variables. If you don't want that, you should use Nowdoc by using single quotes around the first someStringYouWillNeedToStop:

$string = <<<'someStringYouWillAlsoNeedToStop'
curl -A 'Curl/2.5' -d '{"key":"$api_key","message":{"html":"<p><h1>Hello World</h1><\/p>"}'
someStringYouWillAlsoNeedToStop; // this ends your string

Use the escapeshellarg function to guarantee it's fully escaped:

$arg = escapeshellarg('{"key":"$api_key","message":{"html":"<p><h1>Hello World</h1><\/p>"}');
$curl_command = "curl -A 'Curl/2.5' -d '.$arg;