4

I am generating a string dynamically. For example The string looks like this

$string = "this-is-a-test-string-for-example-";

It can also be like this

$string = "this-is-a-test-string-for-example";

I want if there is a hyphen "-" at the end of the string, It should be removed. How can I do that in php or regex?

Munib
  • 3,533
  • 9
  • 29
  • 37

4 Answers4

14

http://pl1.php.net/trim - that function gets characters to trim as last parameter

trim($string,"-");

or as suggested for right side only

rtrim($string,"-");
Ochi
  • 1,468
  • 12
  • 18
2

If it always at the end (right) of the string this will work

$string = rtrim($string,"-");
K. Kilian Lindberg
  • 2,918
  • 23
  • 30
1
$cleanedString = preg_replace('/^(this-is-a-test-string-for-example)-$/', '$1', $string);
tomsv
  • 7,207
  • 6
  • 55
  • 88
0
$delete = array('-');

if(in_array($string[(strlen($string)-1)], $delete))
    $string = substr($string, 0, strlen($string)-1);

You can add other characters to delete into $delete array.

Felipe Francisco
  • 1,064
  • 2
  • 21
  • 45