How to remove part of the line after the last comma in PHP

How to remove part of the line after the last comma in PHP?

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

+4
source share
3 answers

substr and strrpos would be helpful

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

Note: edited based on comments below

+8
source

You want to replace the last comma and the rest of the comma, followed by any other character to the end of the line.

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

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

This is a variant of mario answer , which works if there is no comma in the line.

+4
source
  $ tokens = explode (':', $ string);  // split string on:
 array_pop ($ tokens);  // get rid of last element
 $ newString = implode (':', $ tokens);  // wrap back

+1
source

Source: https://habr.com/ru/post/1415714/


All Articles