2011-11-03 50 views
34

我收到解析錯誤,我認爲這是因爲"time"上的引號引起的。我怎樣才能把它當作一個整體的字符串呢?在PHP中跳轉引號

<?php 

    $text1= 'From time to "time" this submerged or latent theater in 'Hamlet' 
    becomes almost overt. It is close to the surface in Hamlet's pretense of madness, 
    the "antic disposition" he puts on to protect himself and prevent his antagonists 
    from plucking out the heart of his mystery. It is even closer to the surface when 
    Hamlet enters his mother's room and holds up, side by side, the pictures of the 
    two kings, Old Hamlet and Claudius, and proceeds to describe for her the true 
    nature of the choice she has made, presenting truth by means of a show. 
    Similarly, when he leaps into the open grave at Ophelia's funeral, ranting in 
    high heroic terms, he is acting out for Laertes, and perhaps for himself as well, 
    the folly of excessive, melodramatic expressions of grief."; 

    $text2= 'From time to "time"'; 

    similar_text($textl, $text2, $p); 
    echo "Percent: $p%"; 

的問題是,我不能手動每個引號前加\。這是我需要比較的實際文字。

+1

手冊這裏:http://php.net/manual/en/language.types.string.php - 逃逸是相同的大多數其他C風格的語言。 – mario

+1

實際上,上面屏幕截圖中的問題始於Hamlet這個詞之前的單引號,正如着色所暗示的那樣。由於字符串以單引號開頭,因此除了最後一個引號外,所有單引號內部都必須轉義。 因此,第一個變量聲明應該是這樣開始的: ''從時間到'時間'這個......在'哈姆雷特'中的劇院......' $ text2變量實際上很好。 – Goozak

回答

59

使用反斜線這樣

"From time to \"time\""; 

在反斜槓PHP中使用引號中的轉義特殊字符。由於PHP不字符串和字符之間的區別,你也可以使用這個

'From time to "time"'; 

單引號和雙引號之間的區別在於雙引號允許串插,這意味着你可以在字符串中內嵌引用變量及其值會像這樣

$name = 'Chris'; 
$greeting = "Hello my name is $name"; //equals "Hello my name is Chris" 

按你的問題的上次編輯字符串我想你可能能夠做到這一點是使用最簡單的事情進行評估「定界符」。他們不常用,老實說,我通常不會推薦它,但如果你想要一個快速的方式來獲得這一牆文本在一個單一的字符串。語法可以在這裏找到:http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc這裏有一個例子:

$someVar = "hello"; 
$someOtherVar = "goodbye"; 
$heredoc = <<<term 
This is a long line of text that include variables such as $someVar 
and additionally some other variable $someOtherVar. It also supports having 
'single quotes' and "double quotes" without terminating the string itself. 
heredocs have additional functionality that most likely falls outside 
the scope of what you aim to accomplish. 
term; 
1

要麼逃避報價:

$text1= "From time to \"time\""; 

,或者使用單引號來表示你的字符串:

$text1= 'From time to "time"'; 
+0

錯誤的答案。請更正 –

+0

問題是我有這個字符串。 「從時間的‘時間’,男孩會得到'糊塗」 它給出了一個錯誤 – user478636

1
$text1= "From time to \"time\""; 

$text1= 'From time to "time"'; 
+0

請參閱更新問題 – user478636

2

沒有保存文本在PHP文件,但在被稱爲普通的文本文件,說,「的text.txt 「

然後用一個簡單的$text1 = file_get_contents('text.txt');命令讓你的文本沒有一個單一的問題。

+0

實際上,我將有一個函數從doc文件返回文本,如 $ text1 = readDoc(「abc.docx」); //返回文字 這會好嗎? – user478636

+0

如果你將它從任何readDoc(),爲什麼你問的地球如何寫它在線,貶低很多人?! –

+0

對不起,這是我的錯誤,我認爲你可以使用@或字符串開始之前的其他字符,如在C#中。反正它工作。 – user478636

31

使用addslashes功能:

$str = "Is your name O'reilly?"; 

// Outputs: Is your name O\'reilly? 
    echo addslashes($str);