Regex - Trim character at the end of the line

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

<? php

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

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

?>

produces the following:

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

How can I delete a specific trailing character only if it is there, in this case a dash?

Thanks in advance.

+3
source share
3 answers

Use rtrim :

rtrim($str, "-")

If you insist on using regular expressions, you can do

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

The symbol $corresponds to the end of the object.

+10
source

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
+1

, .

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

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

0
source

Source: https://habr.com/ru/post/1747675/


All Articles