简体   繁体   中英

remove trailing backslash from string

I would like to remove the trailing backslash from a string without using stripslashes() or str_replace() . Ideally I would be able to use rtrim() , but its something about the backslashes that has PHP freaking out.

$string = "This is my string\";

//iv'e tried with no success
$clean_string = rtrim($string, "\\");
$clean_string = rtrim($string, "\\\\");

Ideally the string would just read "This is my string" without the backslash at the end. I'm not entirely sure how to escape it properly, any help is much appreciated.

Try this:

 if(substr($string, -1) == "\"){ 
   echo substr($string, 0, -1);
 }

if condition checks whether the last character has slash or not.

You may try preg_replace :

$string = 'This is my string\\';
$clean_string = preg_replace('/(.+)(\\\\)$/', '${1}', $string);

The trailing slash will get removed if pattern is matched. You will get the same string otherwise.

This worked for me:

    if(substr($string, -1) == '\\')
    { 
        $string = substr($string, 0, -1);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM