GGGGG
GGGGG

Reputation: 159

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.

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. even if there are \n or \t or some other special characters in my strings. How can I match this, while taking those special characters into consideration?

Upvotes: 0

Views: 145

Answers (1)

anubhava
anubhava

Reputation: 786081

You will need s flag (DOTALL) to make DOT match new lines:

$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.

Upvotes: 1

Related Questions