0

I'm using rtrim() to remove a part at the end of string, , US in my example:

<?php

$str = "Hello - world, c., US, US";

echo rtrim($str,", US");

?>

Output:

Hello - world, c.

It removed , US, US and i want to remove the last one only and the output should be Hello - world, c., US

How i can do that please?

user2203703
  • 1,955
  • 4
  • 22
  • 36

2 Answers2

4

rtrim() doesn't remove a specific string, it uses the string as a list of characters to remove at the end.

Use a regular expression replacement:

echo preg_replace('/, US$/', '', $str);

The $ anchors the match to the end of the string.

Barmar
  • 741,623
  • 53
  • 500
  • 612
3

substr + strrpos approach:

$str = "Hello - world, c., US, US";
echo substr($str, 0, strrpos($str, ", US"));

The output:

Hello - world, c., US
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105