【问题标题】:Using php preg_replace to remove some punctuations from utf-8 encoded string [duplicate]使用 php preg_replace 从 utf-8 编码字符串中删除一些标点符号 [重复]
【发布时间】:2017-05-10 12:50:28
【问题描述】:

我需要从字符串中删除除括号外的标点符号。我想出了以下几点:

$clean = preg_replace ( "/[^\.\,\-\_\'\"\@\?\!\:\$ a-zA-Z0-9()]/", "", $maybedirty );

这似乎工作正常,直到我意识到我需要通过一些 utf-8 编码字符(东欧)。尽管我找到了一些可能的解决方案的建议,但到目前为止我未能使它们起作用(或理解它们,或两者兼而有之)。所以问题是如何修改正则表达式以允许使用 utf-8 编码字符。

【问题讨论】:

    标签: php regex utf-8 preg-replace


    【解决方案1】:
    $clean = preg_replace('/[^\w\s()]/', '', $maybedirty);
    

    正则表达式解释:

    [^\w\s()]
    
    Match any single character NOT present in the list below «[^\w\s()]»
       A “word character” (Unicode; any letter or ideograph, any number, underscore) «\w»
       A “whitespace character” (any Unicode separator, tab, line feed, carriage return, vertical tab, form feed, next line) «\s»
       A single character from the list “()” «()»
    

    【讨论】:

    • Pedro Lobito 的建议在第一次尝试时不起作用。但是伴随的解释给了我足够的指示要寻找什么,最后我找到了 /u (用于 UTF-8 字符。所以最终的解决方案看起来像这样:$clean = preg_replace('/[^\w\s()]/u', '', $maybedirty); 这个工作,除了它仍然通过下划线,它应该删除。
    • 我很高兴它为你解决了!
    猜你喜欢
    • 1970-01-01
    • 2019-04-30
    • 2015-03-12
    • 2012-09-11
    • 2014-12-19
    • 1970-01-01
    • 2012-05-22
    • 1970-01-01
    • 2014-02-12
    相关资源
    最近更新 更多