3

I am trying to remove a trailing - (dash) at the end of the string. Here is my code:

<?php

$str = 'SAVE $45! - Wed. Beach Co-ed 6s (Jul-Aug)';

echo ereg_replace('([^a-z0-9]+)','-',strtolower($str));

?>

produces this:

save-45-wed-beach-co-ed-6s-jul-aug-

How can I remove a specific trailing character only if its there, in this case the dash?

Thanks in advance.

Torez
  • 1,902
  • 7
  • 25
  • 39
  • You might wanna check this: http://stackoverflow.com/questions/2103797/url-friendly-username-in-php/2103815#2103815 – Alix Axel May 29 '10 at 17:24
  • possible duplicate of [php remove last character if it's a period.](http://stackoverflow.com/questions/2053830/php-remove-last-character-if-its-a-period) – Alix Axel May 29 '10 at 17:29

3 Answers3

11

Use rtrim:

rtrim($str, "-")

If you insist on using regex, you can do

preg_replace('/-$/', '', $str)

The $ character matches the end of the subject.

Artefacto
  • 96,375
  • 17
  • 202
  • 225
1

Another solution.

<?php

$string = 'SAVE $45! - Wed. Beach Co-ed 6s (Jul-Aug)';
$search = array('/[^a-z0-9]+/', '/[^a-z0-9]$/');
$replace = array('-', '');
echo preg_replace($search, $replace, strtolower($string));

?>

Output.

save-45-wed-beach-co-ed-6s-jul-aug
Ramesh Tabarna
  • 539
  • 2
  • 4
0

Your regex is false because it removes every non-alphanumeric characters with a dash.

That should be

echo ereg_replace('-$','',strtolower($str));

$ means "end of string" and the second parameter is the replacement. (At least I think so, I don't know the php ereg_replace function)

Jürgen Steinblock
  • 30,746
  • 24
  • 119
  • 189