2014-01-09 124 views
0

我需要在某些輸入數據中跳過單引號,並且我想在一個函數中執行該函數(該函數還應該包括其他指令,但爲了清晰起見,我不在此處編寫它們)。 所以我寫下面的函數和內部測試了它的輸出和功能外:爲什麼在函數中使用「str_replace」時不起作用?

function quote_skip($data) 
    { 
     $data = str_replace("'", "\'", $data); 
     echo "Output inside the function quote_skip: ".$data." <br>"; 
     return $data; 
    } 
    $test = "l'uomo"; 
    quote_skip($test); 
    echo "Output outside the function quote_skip: ".$test."<br>"; 

結果是follwing:函數quote_strip內部

輸出:L \'外UOMO

輸出函數quote_strip:l'uomo

所以會發生的是,當我在函數外面回顯變量時,反斜槓不再存在。爲什麼會發生?有沒有辦法讓反斜槓也在函數之外?

我只知道php的基礎知識,也許答案很明顯,但我在所有搜索的論壇中都找不到任何東西。如果有人有解決方案,將不勝感激。

謝謝。

+0

謝謝@phihag!我不敢相信這是如此明顯,但我不會自己找到答案。這是一個很大的幫助 – user3178022

回答

5

你忽略了你的函數的

返回值
quote_skip($test); 

want this

$test = quote_skip($test); 
2

功能是沒有問題的,你的代碼波紋管的功能是,當你沒有迴音功能輸出:

$test = "l'uomo"; 
echo "Output outside the function quote_skip: ".quote_skip($test)."<br>"; 
0

它會工作,如果你讓它變量通過引用傳遞:

function quote_skip(&$data) // use the `&` 
{ 
    $data = str_replace("'", "\'", $data); 
    echo "Output inside the function quote_skip: ".$data." <br>"; 
} 

演示:http://phpfiddle.org/lite/code/emr-5ap

相關問題