Elmer Buckley
Elmer Buckley

Reputation: 57

how to define end of string

I want to add "/info" in the end of urls. If the "/info" already exists, I would like to leave as it is.

I'm currently using:

if(strpos($url, "/info") === false){
    $url .= "/info";
}

But the above code works only if the url doesn't contain "/" at the end.

For example: if the url is http://www.domain.com then it works perfectly and the output is http://www.domain.com/info. If the url is http://www.domain.com/ then it shows http://www.domain.com//info.

How to avoid this?

Upvotes: 1

Views: 76

Answers (3)

Shahrokhian
Shahrokhian

Reputation: 1114

consider following url : http://www.domain.com/info/test/

if you use strpos in that way , you will get wrong result. instead you can use substr and rtrim :

$url = (substr($url,-5) != '/info') ? rtrim($url, "/") . '/info' : $url;

Upvotes: 1

Nick Rolando
Nick Rolando

Reputation: 26157

You just need to take that into consideration.

if(substr($url, -5) != '/info') {
  if(substr($url, -1) == "/")
      $url.="info";
  else
      $url.="/info";
}

Note I modified the first if to only check for '/info' at the end of the url; as Gareth did ;)

Upvotes: 1

Gareth Cornish
Gareth Cornish

Reputation: 4356

Trim the domain, then check the last five characters (in case the "/info" string appears elsewhere in the URL).

$url = rtrim($url,'/');
if(substr($url,-5)!='/info') $url .= '/info';

Upvotes: 3

Related Questions