简体   繁体   English

使用php中的正则表达式删除字符后的所有字符

[英]remove all characters after a character using regular expression in php

I need to remove all the characters after the character which I select in a string. 我需要删除在字符串中选择的字符之后的所有字符。 Here is my string 这是我的绳子

$string = "Blow the fun in the sun.paste a random text";
        $new_string = preg_replace("/paste.*/","",$string,-1,$count);
        echo $new_string;

My output is Blow the fun in the sun. 我的输出是Blow the fun in the sun.

If my string is like this 如果我的字符串是这样的

$string = "Blow the fun in the sun.paste \n a random text";
        $new_string = preg_replace("/paste.*/","",$string,-1,$count);
        echo $new_string;

My output is 我的输出是

Blow the fun in the sun.
a random text

But, I need my output as Blow the fun in the sun. 但是,我需要输出作为Blow the fun in the sun. even if there are \\n or \\t or some other special characters in my strings. 即使我的字符串中有\\n or \\t or some other special characters How can I match this, while taking those special characters into consideration? 在考虑那些特殊字符的同时,我该如何匹配?

You will need s flag (DOTALL) to make DOT match new lines: 您将需要s标志(DOTALL)以使DOT匹配新行:

$new_string = preg_replace("/paste.*/"s, "", $string, -1, $count);

Without s flag your regex is not matching new lines as your input contains new lines and you want to replace string that contains new line as well. 没有s标志,您的正则表达式与新行不匹配,因为您的输入包含新行,并且您也想替换包含新行的字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM