2013-01-25 92 views
0

我有這樣的代碼:ereg_replace - 字符串斜槓

<?php 
    $first = '<?xml version=\"1.0\" encoding=\"UTF-8\"?> TEST MESSAGE'; 
    echo ereg_replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", "UPSS", $first); 
?> 

它不工作。我想得到:'UPSS TEST MESSAGE'

我錯了什麼?

+2

Ereg已棄用。檢查http://php.net/manual/en/function.ereg-replace.php(大紅色框:)) –

+0

由於@ VladPreda說,不要使用'ereg_replace()'。它已被棄用。改用'preg_replace()'。話雖如此,在這種情況下,它看起來像你只是想替換一個簡單的字符串,沒有任何複雜的表達式,所以我會說'str_replace()'更好。在正則表達式替換函數中,你需要用正則表達式中的特殊含義來轉義問號和其他字符。 – SDC

回答

3

好了,幾件事情在這裏:

1日問題

你聲明$first用的的'代替",但你逃避你的雙引號,這意味着你結了輸入字符串<?xml version=\"1.0\" encoding=\"UTF-8\"?> TEST MESSAGE(帶反斜槓)。

$first = '<?xml version=\"1.0\" encoding=\"UTF-8\"?> TEST MESSAGE'; 
//  ^   ^^  ^ ^   ^
// You don't need to escape " when using ' to create the string. 

而是要麼

$first = "<?xml version=\"1.0\" encoding=\"UTF-8\"?> TEST MESSAGE"; 
//  ^   ^^  ^ ^   ^
// We escape because we've used " to create the string 

$first = '<?xml version="1.0" encoding="UTF-8"?> TEST MESSAGE'; 
//  ^   ^^  ^ ^   ^
// We do not escape, because we used ' to create the string, and therefore only need to escape '. 

將是正確

第二個問題

您使用ereg_replace。爲什麼?首先,它用於正則表達式,你似乎沒有使用任何的,其次它已被棄用了很長時間,第三,你不餵它的正則表達式。您還在指定替換爲"'s,這意味着您將替換字符串WITHOUT反斜槓,因此找不到匹配項(請記住,\""不一樣)。如果你現在想用正則表達式,看preg_replace,但是你想使用str_replace,而不是看你的問題:

echo str_replace('<?xml version="1.0" encoding="UTF-8"?>', 'UPSS', $first); 
0

嘗試使用str_replace()函數。 如果您的目標是解析內容,則應使用XPath庫。