Removing the last character of a string IF it is $variable [duplicate]
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?
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.
Once you have performed your cleaning up, you can simply use this code to remove trailing underscore:
$mystr = rtrim($text, '_');
$without_starting_or_ending_underscores = trim($original, '_');
If you only want to remove trailing ones, use rtrim()
instead.
Check out rtrim.
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
精彩评论