2013-10-17 61 views
0

我如何可以采取一个字符串,有很多混合双人和单引号的:创建一个字符串变量,是包含混合报价

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

,并创建一个字符串变量,例如:

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

没有返回“意外”错误“?我想避免更改原始字符串。

+0

我想在我的php文件中使用php $ variables在json部分中进行硬编码。 – JMC

回答

3

您可以使用heredoc语法并轻松地转义所有引号和双引号。

下面是它的语法。 http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc

注意不要在heredoc标识符之前留出空格。

+0

EOD和EOT有什么区别? – JMC

+1

@JMC看到我的回答,你会明白......没有区别。不要紧,你用什么。你可以使用'EOD','EOT','blahblah',甚至'someStringYouWillAlsoNeedToStop' –

+0

谢谢我现在得到它。它们在手册中的EOD和EOT之间切换,使其看起来有意义。 – JMC

1

利用HEREDOC句法。

<?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:

卷曲-A '卷曲/ 2.5' -d“{ “关键”: “xx2233”, “消息”:{ “HTML”:”你好世界

</p>“}

1

您可以使用定界符:

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

请注意,heredoc DOES会解析您的$变量。 如果你不希望出现这种情况,你应该使用Nowdoc通过围绕第一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 
+0

+1用于阐述和包含Nowdoc信息 – JMC

0

使用escapeshellarg功能,以保证它的完全逃脱:

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