Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 942
walter Avatar asked Dec 30 '10 09:12

walter


People also ask

How do I trim a string after a specific character in PHP?

The substr() and strpos() function is used to remove portion of string after certain character. strpos() function: This function is used to find the first occurrence position of a string inside another string. Function returns an integer value of position of first occurrence of string.

How does preg_ replace work?

The preg_replace() function returns a string or array of strings where all matches of a pattern or list of patterns found in the input are replaced with substrings.

What is the difference between Str_replace and Preg_replace?

str_replace replaces a specific occurrence of a string, for instance "foo" will only match and replace that: "foo". preg_replace will do regular expression matching, for instance "/f. {2}/" will match and replace "foo", but also "fey", "fir", "fox", "f12", etc.


1 Answers

The following would be much faster;

$str = 'merry_christmas';
$str = substr($str, 0, strpos($str, '_'));
like image 102
Erik Avatar answered Sep 20 '22 07:09

Erik