我试图让preg_replace完全删除消息中的字符串
下面是$消息的示例:
hello there john214
welcome to the site!
please get feel free to kick back and relax.
Run Code Online (Sandbox Code Playgroud)
where john214是通过db输出的用户名
现在我想摆脱hello there john214使用preg_replace,但是,我的代码除了删除所有内容john214
继承我的代码:
$message = preg_replace('|hello there (.*?)|si', '', $message);
Run Code Online (Sandbox Code Playgroud)
为什么不删除john214?
这可能是因为你正在做一个非贪婪的方法.试试这个:
$message = preg_replace('|hello there(.*)|si', '', $message);
Run Code Online (Sandbox Code Playgroud)
这将摆脱一切之后去hello there(因为修饰符S).但是,如果你想要的是在一行之后摆脱一切hello there,你想要摆脱s修饰符:
$message = preg_replace('|hello there(.*)|i', '', $message);
Run Code Online (Sandbox Code Playgroud)
如果你使用s修饰符,你就会使Dot元字符匹配换行符,这就是为什么第一个正则表达式会消耗掉hello之后的所有内容(甚至跳到新行).