phpstring

How to remove last char in oversized string php


Something strange happens here, I have for example a string printend by var_dump:

 string(83) "papillon"

This string has a length oversized, is 83, the real is 8. Anyway some strings have a ! in final position : papillon! If they has just 1 or more then 1 of ! i have to remove the last.

 if(substr_count($tit, '!') >= 1){
            $tit = str_replace('!','',$tit);
          }

This is not correct, also i can't use substr() becouse of the size. So how I can remove the last occurence of a specific char in a string?


Solution

  • So, there are a couple of options;

    Opt A : rtrim
    So, if you have;

    $my_string = "This is a really long string!!!";
    print rtrim($my_string, "!");
    // Printed; This is a really long string
    

    This removes all occurrences of the mask of chars chosen

    Opt B : regex with preg_replace
    So, again we have the following string and work;

    $my_string = "This is a really long string!!!";
    print preg_replace("/(.+)(!){1}/i", "$0", $my_string);
    // Printed; This is a really long string!!
    

    Using preg_replace only removes the final occurrence of the "!" in the string, leaving you with 2 remaining

    This greatly depends on what you need and of course there are other options such as substr, as follows;

    $my_string = "This is a really long string!!!";
    print substr($my_string, 0, -1);
    // Printed; This is a really long string!!
    

    So that worked the same as preg_replace, but you could also count the amount of exclamation points and removed as needed

    So, I went away and realised I was using a JavaScript regex playground rather than PHP which caused issues... (oops!)
    To which end, I came up with the following when messing around on a PHP testbed as shown in my working out

    $my_string = "This is a really long string!!!";
    print preg_replace("/(.[!]{1})[!]{0,}/i", "$1", $my_string);
    

    This removes every "!" except one, if you wanted all gone, change to;

    $my_string = "This is a really long string!!!";
    print preg_replace("/(.)[!]{0,}/i", "$1", $my_string);
    

    It doesn't matter how many additional "!" there are (I've tested with 103), either all, or all but one will be removed