Find last character in a string in PHP

前端 未结 7 1876
粉色の甜心
粉色の甜心 2020-12-15 09:02

I\'m doing some url rewriting in PHP and need to find URLS with a slash at the end and then do a 301 redirect. I thought there\'d be a simple PHP function to find last stri

相关标签:
7条回答
  • 2020-12-15 09:44

    $string[strlen($string)-1] gives you the last character.

    But if you want to strip trailing slashes, you can do $string = rtrim($string, '/');. If there is no trailing slash, $string will remain unchanged.

    0 讨论(0)
  • 2020-12-15 09:50

    You can use substr:

    substr($str, -1)
    

    This returns the last byte/character in a single-byte string. See also the multi-byte string variant mb_substr.

    But if you just want to remove any trailing slashes, rtrim is probably the best solution.

    And since you’re working with URLs, you might also take a look at parse_url to parse URLs as a trailing slash does not need to be part of the URL path.

    0 讨论(0)
  • 2020-12-15 09:51

    If you have php > 7.1

    $string[-1]
    

    Will give you the last character

    http://sandbox.onlinephpfunctions.com/code/ff439889f14906749e4eb6328796c354c60f269b

    0 讨论(0)
  • 2020-12-15 09:55

    A nice solution to remove safely the last / is to use

    $string = rtrim($string, '/');
    

    rtrim() removes all /s on the right side of the string when there is one or more.

    You can also safely add exactly one single / at the end of an URL:

    $string = rtrim($string, '/').'/';
    
    0 讨论(0)
  • 2020-12-15 09:55

    You can use basename()

    This will return characters for http://domainx.com/characters/ as well as http://domainx.com/characters

    You can do like this:-

    $page = $_SERVER['REQUEST_URI'];
    $module = basename($page);
    

    Then you can use the $module directly in your conditional logic without doing any redirects.

    If you want to collect the last / trimmed URL then you can do this:-

    If you are storing the project base url in a config file:-

    BASE_URL  = 'http://example.com'
    

    then you can do this:-

    $page = $_SERVER['REQUEST_URI'];
    $module = basename($page);
    $trimmedUrl = BASE_URL.'/'.$module;
    
    0 讨论(0)
  • 2020-12-15 10:00

    With PHP 8

    str_ends_with($string, '/');
    

    New str_starts_with() and str_ends_with() functions are added into the core.

    0 讨论(0)
提交回复
热议问题