【问题标题】:preg_replace not replacing everythingpreg_replace 不替换所有内容
【发布时间】:2011-10-05 04:11:52
【问题描述】:

我试图让 preg_replace 从消息中完全删除字符串

这里是 $message 的示例:

hello there john214

welcome to the site!

please get feel free to kick back and relax.

其中john214是通过db输出的用户名

现在我想使用 preg_replace 删除 hello there john214,但是,我的代码正在删除除 john214 之外的所有内容

这是我的代码:

$message = preg_replace('|hello there (.*?)|si', '', $message);

为什么不删除john214

【问题讨论】:

    标签: php preg-replace


    【解决方案1】:

    这可能是因为你正在做一个非贪婪的方法。试试这个:

    $message = preg_replace('|hello there(.*)|si', '', $message);
    

    这将删除hello there 之后的所有内容(因为S modifier)。但是,如果您想要删除hello there 之后的单行 中的所有内容,则需要删除s 修饰符:

    $message = preg_replace('|hello there(.*)|i', '', $message);
    

    如果您使用 s 修饰符,您正在使 Dot metacharacter 匹配换行符,这就是为什么第一个正则表达式将消耗 hello 之后的所有内容(甚至跳转到新行)。

    【讨论】:

    • 请注意,直到 字符串的结尾 与带有s 修饰符的行尾 不同。
    • 我想通了:preg_replace('|hello there (.*?)(\s)|si', '', $message);
    • 您想删除 s 修饰符。这将使.* 包含换行符,这些换行符将转到字符串的末尾而不是行尾。
    【解决方案2】:

    摆脱?和“s”:

    $message = preg_replace('~hello there .*~i', '', $message);
    

    还有,“|”对于分隔符来说是一个糟糕的选择,因为“|”在正则表达式语言中是特殊的

    【讨论】:

    • 完全同意“|”分隔符。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多