1

I've a very strange problem. my script cut the last > and i don't know why.

<?php

$string = "<a href='#'>Test</a>" . "<br>";
$string = rtrim($string, "<br>");

var_dump($string);

// OUTPUT

string '<a href='#'>Test</a' (length=19)

// INSTEAD

string '<a href='#'>Test</a>' (length=20)

I need to remove THE LAST <br> in the string (if present) and only if is the tail of the string.

Example:

$string = "<a>CC</a><br><a>CC</a>" //is ok
$string = "<a>CC</a><br><a>CC</a><br>" // --> <a>CC</a><br><a>CC</a>
Giuseppe Lodi Rizzini
  • 1,045
  • 11
  • 33
  • 2
    `rtrim` doesn't treat its second argument as a string, but as a list of characters. So it'll remove all instances of of `<`, `b`, `r`, and `>` from the end of the string. – iainn May 18 '18 at 13:41
  • 1
    Possible duplicate of [Remove a part of a string, but only when it is at the end of the string](https://stackoverflow.com/questions/5573334/remove-a-part-of-a-string-but-only-when-it-is-at-the-end-of-the-string) – iainn May 18 '18 at 13:41
  • Ops i've always used Rtrim in bad way then!! :( – Giuseppe Lodi Rizzini May 18 '18 at 13:43
  • @GiuseppeLodiRizzini Yep, you did. I have corrected it. Feel free to use my code. – Praveen Kumar Purushothaman May 18 '18 at 13:43

1 Answers1

3

The second parameter is not a delimiter but a character mask. So, it will definitely trim off any of the strings, individually.

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. With .. you can specify a range of characters.

You have to remove it with either str_replace(), if there's only one <br>:

str_replace("<br>", "", $string);

Or you need to use RegExp:

preg_replace('/<br>$/', "", $string);
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252