PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, January 17, 2022

[FIXED] php checking if the last character is a '/' if not then tack it on

 January 17, 2022     php     No comments   

Issue

I have these 2 snippets of code that I have been playing with, but can't seem to get the logic to stick in either of them.

I am trying to see if a given string has a '/' at the end, if not then add it.

$path = '.';

if (substr($path, 0, -1) != '/')
    $path .= '/';

and

if (strrpos('/', $path) !== true)
    $path .= '/';

the issue im having is that if i make $path equal to './ then I get this as the output .//

this is the snippet of where i am having the issue

if (!is_array($paths))
    $this->classPath[] = $paths;
else
    $this->classPath = $paths;

foreach ($this->classPath as $path) {

    if (strrpos('/', $path) !== true)// || substr_count($path, '/') >= 0)
        $path = $path . '/';
    //else
        //$this->classPath[] = $path;
        //echo '0';
    $pathArr[] = $path;

Solution

You might be overthinking it. While the substr() method will work perfectly it might be simpler to use rtrim() to remove any trailing slashes and then add one on.

$path = rtrim($path, '/') . '/';

Caution: this will trim multiple trailing forward slashes. so .////// becomes ./



Answered By - Mike B
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing