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,263
  • 8
  • 26
  • 35

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,774
  • 22
  • 29
1
$cleanedString = preg_replace('/^(this-is-a-test-string-for-example)-$/', '$1', $string);
tomsv
  • 7,017
  • 5
  • 52
  • 87
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,025
  • 1
  • 19
  • 41