PDA

View Full Version : Resolved trim() www. taking another w



SaishuHane
02-20-2013, 12:30 AM
For the life of me, I can't understand why trim() takes off more than I'm asking for. All I want removed is www. from a string, but in the event of www.w, it takes that off too. This is what I have:


trim('www.wt', 'www.');

This results in t



trim('www.rwt', 'www.');

This results in rwt

I've since just started using substr to take out the first four, but it will absolutely keep me up at night not knowing why it keeps taking that extra w.

james438
02-20-2013, 01:10 AM
The portion to be removed is the character list not a string. For example


trim('www.wt', 'www.');
is the same as

trim('www.wt', 'w.');

In regards to your second example remember that trim will trim the selected characters from the beginning and end of your string. If a letter is removed from the end or beginning of your string and the next character is also part of the character list then it too will be removed. Since the "w" is between an "r" and a "t" and neither the "r" or the "t" are part of the character list. That "w" will not be removed. It will not be removed because at no point is it located at the beginning or end of the string.

Does that help explain it?

SaishuHane
02-20-2013, 01:23 AM
Thank you much! I didn't quite get it at first, but after testing some things based on what you said, I'm not going to be losing any sleep tonight!

james438
02-20-2013, 01:32 AM
Happy to help :)

djr33
02-20-2013, 02:05 AM
Did you work this out? You can do this, but it will need to be done in a slightly different way.

One option would be the following:

$str = str_replace('www.','%',$str);
trim($str,'%');
$str = str_replace('%','www.',$str);
Just make sure you don't have any other '%' characters in your string (or use something else as the placeholder).


However, there may be a better way to reach your overall goal. That's just if you specifically want to use trim().