2014-10-06 28 views
0

我有一個PHP字符串:引號內的引號 - 作爲字符串?

$str = ''; 

我需要有一些這方面的HTML,但HTML有「引號內的引號。如何處理這種情況?

的HTML是:

data-setup="{'example_option':true}" 
+0

使用「\」字符轉義行情 – 2014-10-06 11:54:33

+0

是事先知道的HTML的格式? – 2014-10-06 11:55:00

+0

如果你不想有任何轉義問題,你可以使用heredocs。他們不是很舒適,但如果你有一個靜態的長字符串解析他們可能會成爲一個很好的解決方案。但是,在你的情況下,通過在它之前加一個反斜槓就可以將每個''''轉義出來:'\「'就完成了。 – briosheje 2014-10-06 12:02:47

回答

1

對付引號內的報價,你需要逃避他們是這樣的:

echo "<a href=\"somelink.html\">Link</a>"; 

簡單地說:

\" tells php to simply echo out the " as a quote instead of handling it as a part of the code. 

您的字符串:

$string = "data-setup=\"{'example_option':true}\"" 
echo $string; 
// Output: 
data-setup="{'example_option':true}" 
+0

你能告訴我一個我的代碼示例,我已經厭倦了逃避它,但它仍然無法工作。 – panthro 2014-10-06 11:59:44

+0

更新了我的回答 – 2014-10-06 12:01:32

+0

它會讓我接受。謝謝 – panthro 2014-10-06 12:03:40

0

您還可以使用HEREDOC

<?php 
$html = <<<EOD 
     data-setup="{'example_option':true}" 
EOD; 

echo $html; 
0

看起來你想從PHP的一些數據傳遞給通過data-attribute視圖。我建議您使用json_encode,並將您的數據構建爲普通的PHP數組,而不必擔心會引用引號或其他惡意內容。

<html> 
    <head> 
     <script src="//code.jquery.com/jquery-1.11.0.min.js"></script> 
    </head> 
    <body> 
     <?php 

      $data = array(
        'example_option' => true, 
        'some_html'  => '<b>"Hello & good day!"</b>', 
       ); 

      // avoid escaping from the JS parser 
      $str = json_encode($data, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT); 
      ?> 

     <a data-setup='<?php echo $str; ?>' href="#">This link has awesome data</a> 
    </body> 
</html> 

然後,你可以訪問存取數據很容易屬性(我確實有很大的假設,在這裏,你正在使用jQuery)。