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
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.
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.
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.
The following would be much faster;
$str = 'merry_christmas';
$str = substr($str, 0, strpos($str, '_'));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With