-1

How does rtrim work? I have a string "4dbb3dca&". I am not sure how my string is formmated. I want to call rtrim('4dbb3dca&', '&')

--edit:& might be $amp; special character issue

But after my string is 4dbb3dc.

I expect it to be 4dbb3dca.

Is there any workaround? I ried to use &, but then rtrim does nothing and initial string is returned. Is it possible to use rtrim in my situation? Does it depend on php version?

--- edit ---

after some research I realized that I want: I want remove & using & in rtrim() function. Is this possible?

Aipo
  • 1,805
  • 3
  • 23
  • 48

4 Answers4

5

Q1. Is it possible to use rtrim in my situation? Yes, it is possible to use rtrim() in your situation.

Q2. Does it depend on php version? No

You just need to use echo rtrim('4dbb3dca&', '&'); not the & because 2nd parameter of rtrim works like below-

You can also specify the characters you want to strip, by means of the character_mask parameter. Simply list all characters that you want to be stripped

DEMO: https://3v4l.org/anFIR

If you use this below example, then you'll get the same result because it'll try to remove all the given character(s) from the right side of your given string. For Ex-

echo rtrim('4dbb3dca&;pm', '&');` // will also return 4dbb3dc
A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103
1

The second string you specify in rtim() contains all the extra characters you want to trim. So the chars getting trimmed are "&" and "a" (both are indeed included in the second parameter of your rtrim() function call, "&amp").

To get the result that you want, you should invoke rtrim() this way:

rtrim('4dbb3dca&', '&')
Ass3mbler
  • 3,855
  • 2
  • 20
  • 18
1

It looks like you're trying to remove an ampersand from the end of the string, potentially in encoded form. rtrim doesn't give you enough control to do that, as you've seen, but you can do it with preg_replace.

echo preg_replace('/&(amp;)?$/', '', $string);

The pattern will match an ampersand at the end of the string, optionally followed by amp;.

Don't Panic
  • 41,125
  • 10
  • 61
  • 80
1

The way the rtrim works remove the last characters at the second argument.

the PHP has split the string to characters and make a check if you have the characters at last of the string.

if you have two characters from the list of characters the rtrim will remove both

For example :

;&apm it will be the same result like &

if you want to remove the only ampersand symbol at the end of the string use this code: rtrim('4dbb3dca&','&');

for understand more you can read about it at php.net http://php.net/manual/en/function.rtrim.php

eyal
  • 42
  • 6