在PHP中查找字符串中的最后一个字符 [英] Find last character in a string in PHP
问题描述
我在PHP中做一些url重写,需要找到带有斜杠的URLS,然后做一个301重定向。我想有一个简单的PHP函数找到最后一个字符串,但我找不到任何东西。第一本能使m认为我需要使用regex,但我不是100%。
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 string, but I couldn't find anything. First instincts make m think I need to use regex, but I'm not 100%.
这里有一个例子:
http://domainx.com/characters/ 我想找到一个尾部斜杠,并将其转成 http://domainx.com/字符
http://domainx.com/characters/ I want to find a trailing slash and turn it into http://domainx.com/characters
那么,什么函数可以帮助我检查最后一个字符是否为/?
So what function will help me check if the last character is a "/"?
推荐答案
安全删除最后一个 /
的好方法是使用
A nice solution to remove safely the last /
is to use
$string = rtrim($string, '/');
rtrim()
删除字符串右侧的所有 /
有一个或多个。
您还可以安全地在网址末尾安全添加一个 /
:
You can also safely add exactly one single /
at the end of an URL:
$string = rtrim($string, '/').'/';
这篇关于在PHP中查找字符串中的最后一个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!