3

I've made a little script to convert titles into url friendly things.

ie:

'I am a title'

becomes

'I_am_a_title'

My script basically goes through and turns spaces, apostrophes, commas etc etc into an underscore.

The problem is, sometimes my url's end up like this:

'i_am_a_title_'

with a trailing underscore...

So i figure, add a little bit to go through and search to see if the last character is an underscore on the final result, and if it is, then swap it.

I looked into the strrchr() function but I seem to be hitting a wall of my own understanding.

How is this sort of thing accomplished?

Shaun
  • 4,789
  • 3
  • 22
  • 27
willdanceforfun
  • 11,044
  • 31
  • 82
  • 122
  • You probably want to use the [`trim()`](http://php.net/manual/en/function.trim.php) command on the string before you process it. `trim()` removes whitespace (and other characters you specify) on the beginning and end of a string. – Reese Moore Jan 16 '11 at 07:42

5 Answers5

16

PHP's trim() function will do what you need it to, on both sides of the string:

$slug = trim($slug, '_');

You could even run this before changing special characters to underscores if you wanted to, as the function can handle trimming multiple different characters off.

PleaseStand
  • 31,641
  • 6
  • 68
  • 95
  • 1
    Second answer is correct. The example is an underscore, but the question is for any variable, only on the end of the string. That means you should use rtrim instead of trim. – ftrotter Sep 09 '18 at 15:40
5

Once you have performed your cleaning up, you can simply use this code to remove trailing underscore:

$mystr = rtrim($text, '_');
Sarfraz
  • 377,238
  • 77
  • 533
  • 578
3
$without_starting_or_ending_underscores = trim($original, '_');

If you only want to remove trailing ones, use rtrim() instead.

Amber
  • 507,862
  • 82
  • 626
  • 550
1

Check out rtrim.

Yzmir Ramirez
  • 1,281
  • 7
  • 11
1

Something like this,

YOUR_STRING=rtrim(YOUR_STRING,'_');

rtrim will remove specified chars from the end of you string. http://php.net/manual/en/function.trim.php

/Viktor

Viktor
  • 476
  • 3
  • 16