2014-08-30 44 views
-1

如何在單個函數中預先加載反斜槓中的某些字符?PHP對預定義字符集的addslashes

做了一堆str_replace S的等效:

$text = "asdf[],.\?'"; 
$text = str_replace("'","\'", $text); 
$text = str_replace("s","\s", $text); 
$text = str_replace("[","\[", $text); 
...etc... 

我想在一個字符類通過像正則表達式,但不知道如何有preg_replace前面加上反斜槓,而不是替換它。

$text = preg_replace("/['s\[]/","\{$var?}",$text); 

我可以在數組中設置字符並循環它,但我似乎記得一個功能,只是這樣做。

+0

BTW:請注意,'str_replace()函數''接受作爲array'參數也 – 2014-08-30 18:06:56

回答

4

使用addcslashes()如果你想用一個反斜槓逃脫單個字符:

$text = "asdf[],.\?'"; 
echo addcslashes($text, "'s["); 

輸出:

a\sdf\[],.\?\' 

Demo

+1

+1。毆打一拳。這是使用的正確功能。 – 2014-08-30 18:07:37

+0

謝謝,正是我在找的東西。 – 2014-08-30 18:08:31

1

只需添加四個反斜槓在更換零件,

<?php 
$text = "asdf[],.\?'"; 
echo preg_replace("/(['s\[])/","\\\\$1",$text); 
?> 

輸出:

a\sdf\[],.\?\' 
+2

爲什麼要重塑'addcslashes'已經做了什麼? – hwnd 2014-08-30 18:11:22

+2

只是另一種解決方案.. – 2014-08-30 18:12:00

+1

如果您需要轉義更復雜的字符序列,則正則表達式是一個不錯的選擇。例如,將'ba'轉義爲'\ ba'。正則表達式在這裏閃耀。 – goat 2014-08-30 18:15:18