简体   繁体   English

从字符串中删除尾部反斜杠

[英]remove trailing backslash from string

I would like to remove the trailing backslash from a string without using stripslashes() or str_replace() .我想在不使用stripslashes()str_replace()情况下从字符串中删除尾部反斜杠。 Ideally I would be able to use rtrim() , but its something about the backslashes that has PHP freaking out.理想情况下,我将能够使用rtrim() ,但它与反斜杠有关,使 PHP 吓坏了。

$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. if 条件检查最后一个字符是否有斜线。

You may try preg_replace :你可以试试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);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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