2012-06-06 77 views
0

我把這些句子從PHP手冊:轉義反斜槓字符引用的字符串

'this is a simple string', 
'Arnold once said: "I\'ll be back"', 
'You deleted C:\\*.*?', 
'You deleted C:\*.*?', 
'This will not expand: \n a newline', 
'Variables do not $expand $either' 

我想用PHP代碼來呼應他們,正是因爲他們的出現,與轉義的單引號(像第二句)和雙反斜線(如第三句)。這是我到目前爲止有:

<?php 

$strings = array(
     'this is a simple string', 
     'Arnold once said: "I\'ll be back"', 
     'You deleted C:\\*.*?', 
     'You deleted C:\*.*?', 
     'This will not expand: \n a newline', 
     'Variables do not $expand $either'); 

$patterns = array('~\\\'~', '~\\\\~'); 
$replacements = array('\\\\\'', '\\\\\\\\'); 

foreach($strings as $string) 
{ 
     echo '\'' . preg_replace($patterns, $replacements, $string) . '\'' . '</br>'; 
} 
?> 

輸出是:

'this is a simple string' 
'Arnold once said: "I\\'ll be back"' 
'You deleted C:\\*.*?' 
'You deleted C:\\*.*?' 
'This will not expand: \\n a newline' 
'Variables do not $expand $either' 

,但我想正好呼應琴絃,因爲他們在我的代碼,如果有可能上市。我遇到雙反斜槓字符(\)的問題。我的第二個模式('〜\\〜')似乎取代了單雙反斜槓。我也嘗試使用addcslashes()具有相同的結果。

(我問這個問題最近在其他地方,但沒有一個解決方案)

在此先感謝。

+0

這可能是不可能的。我不知道它是如此,但我認爲PHP不會存儲字符串的原始格式,僅存儲內容。在這種情況下,在示例中沒有辦法對句子#3和#4進行區分。 – JJJ

+0

謝謝你的評論,如果是這樣,倒黴我! – Anonimista

回答

2

,而不是與preg_replace()插手,可以考慮使用var_export()打印字符串的 「真實副本」:

foreach ($strings as $s) { 
    echo var_export($s, true), PHP_EOL; 
} 

輸出:

'this is a simple string' 
'Arnold once said: "I\'ll be back"' 
'You deleted C:\\*.*?' 
'You deleted C:\\*.*?' 
'This will not expand: \\n a newline' 
'Variables do not $expand $either' 

由於你可以看到,句子3和4與PHP相同。

+0

在第三句話中,我仍然留有一個額外的反斜槓,但看起來這個距離已經很近了。感謝所有回答我的問題。 – Anonimista

1

試試看看這個代碼。它按預期工作。

<?php 

$strings = array(
    'this is a simple string', 
    'Arnold once said: "I\'ll be back"', 
    'You deleted C:\\*.*?', 
    'You deleted C:\*.*?', 
    'This will not expand: \n a newline', 
    'Variables do not $expand $either'); 

$patterns = array('~\\\'~', '~\\\\~'); 
$replacements = array('\\\\\'', '\\\\\\\\'); 

foreach($strings as $string){ 
    print_r(strip_tags($string,"\n,:/")); 
    print_r("\n"); 
} 
?> 

您可以在strip_tags中指定allowable_tags。請參閱strip_tags做進一步的瞭解 這裏是DEMO

+0

感謝您的回答。我需要完全按照它們輸出字符串,即。用單引號和輸入字符串的所有字符括起來。所以我在第三句中需要兩個反斜槓,而在第二句中,文本應該包含「我會回來的」(帶有反斜槓)。 – Anonimista