Trim a PHP string before the last special character

This small PHP function is helping us to get only a part of a value (string) by using a specific character as an indicator.

How do I get only the last part of a value?

We can use the following function to get only a value after the last character we’ve passed to the function. For example, $string = "123456"; is the start value and $character = "5"; the last character we use to get the part, after exactly that character.

An example:

In this example, the start value is a URL and in result we only want to get the attached parameter value.

  • Start value: https://domain.com/?color=black
  • End Value: color=black

An additional example:

In this example, we have a text string as start value and we only want to get the gender.

  • Start value: I’m male
  • End Value: male