How to use preg_replace to remove anything from a certain character on until the end of a string?

walter picture walter · Dec 30, 2010 · Viewed 24k times · Source

Hi I need to remove all characters from the '_' until the end of the string.

I tried with:

$string = 'merry_christmas';

$string = preg_replace('/_*/','',$string);

echo $string; // I need it to be: 'merry'

...but nope.

The idea is to remove the underscore character '_' and all characters to the its right.

Thanks

Answer

Erik picture Erik · Dec 30, 2010

The following would be much faster;

$str = 'merry_christmas';
$str = substr($str, 0, strpos($str, '_'));