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

时间:2014-03-14 12:09:16

标签: php regex

我需要删除我在字符串中选择的字符后面的所有字符。 这是我的字符串

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

我的输出是Blow the fun in the sun.

如果我的字符串是这样的

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

我的输出是

Blow the fun in the sun.
a random text

但是,即使我的字符串中有Blow the fun in the sun.,我也需要输出\n or \t or some other special characters。如何考虑这些特殊字符,我该如何匹配呢?

1 个答案:

答案 0 :(得分:1)

您需要s标志(DOTALL)才能使DOT与新行匹配:

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

如果没有s标记,则正则表达式与新行不匹配,因为您的输入包含新行,并且您想要替换包含新行的字符串。