Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

regex - Find last character in a string in PHP

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%.

Here's one example:

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 "/"?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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, '/').'/';

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...