Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove part of a string after last comma in PHP

How to remove part of a string after last comma in PHP ?

String : "this is a post, number 1, date 23, month 04, year 2012"
Expected: "this is a post, number 1, date 23, month 04"

like image 787
premtech11 Avatar asked Dec 01 '22 22:12

premtech11


2 Answers

substr and strrpos would be useful

$until = substr($string, 0, strrpos($string.",", ","));

Note: edited based on comments below

like image 137
mario Avatar answered Dec 22 '22 05:12

mario


You want to replace the last comma and the rest, that is a comma followed by any other character until the end of the string.

This can be formulated as a regular expression and that pattern can be replaced via preg_replace with an empty string:

$until = preg_replace('/,[^,]*$/', '', $string);

This is a variant of mario's answer that works in case there is no comma in the string as well.

like image 23
hakre Avatar answered Dec 22 '22 04:12

hakre