2011-03-28 98 views
8

当我运行,通过该功能,它与QUOT更换引号包含双引号短语删除单引号和双引号。如何从一个字符串

我要彻底删除它们(也单引号)。我如何改变功能来做到这一点?

function string_sanitize($s) { 
    $result = preg_replace("/[^a-zA-Z0-9]+/", "", $s); 
    return $result; 
} 

更新:

Example 1: This is 'the' first example 
returns: Thisis030the039firstexample 
Errors: Warning: preg_match_all() [function.preg-match-all]: Unknown modifier '0' in C 


Example 2: This is my "second" example 
returns: Thisismyquotsecondquotexample 
Errors: Invalid express in Xpath 
+0

此功能已经削减了两个'''和'“' – zerkms 2011-03-28 03:14:53

回答

12

它看起来像你的原始字符串有HTML字符""),所以当你试图清理它,你只需删除&;,留下字符串quot的其余部分。

---编辑---

大概除去非字母数字字符是将HTML字符html_entity_decode进行解码,然后通过正则表达式运行它的最简单的方法。因为在这种情况下,您不会得到需要重新编码的任何内容,因此您不需要再执行htmlentities,但值得记住的是,您的的HTML数据,而您现在有未编码的原始数据。

如:

function string_sanitize($s) { 
    $result = preg_replace("/[^a-zA-Z0-9]+/", "", html_entity_decode($s, ENT_QUOTES)); 
    return $result; 
} 

注意ENT_QUOTES标志的功能 “......都转换双人和单引号。”

+0

哦。好猜测。 – 2011-03-28 03:23:18

+0

+1大点和观察。任何想法我怎么能剥夺"e;呢? – 2011-03-28 03:26:12

+0

用你如何做的例子编辑。 – Hamish 2011-03-28 03:32:31

0

你的函数使用正则表达式,以消除任何字符,从[A-ZA-Z0-9]不同的,所以它一定删除任何“”或“”

编辑:好了,从麦答案,我意识到你字符串是一个HTML字符串,所以它解释了为什么“(& QUOT)被转化为‘QUOT’。你可以考虑更换通过了preg_replace &quote,或htmlspecialchars_decode第一。

24

我不会调用该函数string_sanitize(),因为它是一种误导。你可以把它strip_non_alphanumeric()

您目前的功能将去除任何不是大写或小写字母或数字的东西。

可以大道仅有'"与...

$str = str_replace(array('\'', '"'), '', $str); 
+0

简单而好的解决方案 – Praveen 2017-05-02 09:04:33

1

我觉得你的preg_replace调用应该是这样的:

$result = preg_replace("/[^a-zA-Z0-9]+/", "", html_entity_decode($s)); 

请参阅html_entity_decode reference了解更多详情。

0

为了确保删除所有种类的报价(包括在其中左侧是从右侧的人不同),我想那一定是这样的;

function string_sanitize($s) { 
    $result = htmlentities($s); 
    $result = preg_replace('/^(")(.*)(")$/', "$2", $result); 
    $result = preg_replace('/^(«)(.*)(»)$/', "$2", $result); 
    $result = preg_replace('/^(“)(.*)(”)$/', "$2", $result); 
    $result = preg_replace('/^(')(.*)(')$/', "$2", $result); 
    $result = html_entity_decode($result); 
    return $result; 
}