Regex to convert directory paths in PHP - php

Goal -
convert a path: /aaaaa/bbbbb/ccccc/dddd
to a relative path (to the root): ../../../../
So far I've come up with this regex: /\/.+?\//
but this only produces: ..bbbbb..dddd because it is only matching every other pair of slashes, and also matching the slashes. I'm looking for something like a string split, but also replace.
All of my php code:
$pattern = '/\/.+?\//';
$path = '/aaaaa/bbbbb/ccccc/dddd';
echo preg_replace($pattern, '..', $path);

preg_replace('/\/{0,1}(\w+)\/{0,1}/', '../', $path);
This is working for me.

How about:
preg_replace(':/[^/]+:', '../', $path);

what about the below ?
$pattern = '/\//';
$path = '/aaaaa/bbbbb/ccccc/dddd';
preg_replace(array($pattern), array('..'), $path

Related

Get only the filename from a path

I have this string
$string = 'C:\Folder\Sub-Folder\file.ext';
I want to change it to:
$string = 'file.ext';
Using PHP, I am trying to write a method that ignores everything left of the last \.
Use basename() with str_replace() as the \ in the path is not recognized by basename()
$filename = basename(str_replace('\\', '/', 'C:\Folder\Sub-Foler\file.ext'));
echo $filename; // file.ext
Demo
Another solution is this:
Split the string by a delimiter(\) to form an array: ['C:', 'Folder', 'Sub-Foler', 'file.ext'] using explode: explode("\\", $string);
Get the last element in the array using the end function, which you want as the result.
Put it all together:
$string = 'C:\Folder\Sub-Foler\file.ext';
$stringPieces = explode("\\", $string);
$string = end($stringPieces);
Here's a demo: http://3v4l.org/i1du4

PHP regular expression for directory

I need a regular expression that would take the string after the last forward slash.
For example, considering I have the following string:
C:/dir/file.txt
I need to take only the file.txt part (string).
Thank you :)
You don't need a regex.
$string = "C:/dir/file.txt";
$filetemp = explode("/",$string);
$file = end($filetemp);
Edited because I remember the latest PHP spitting errors out about chaining these types of functions.
If your strings are always paths you should consider the basename() function.
Example:
$string = 'C:/dir/file.txt';
$file = basename($string);
Otherwise, the other answers are great!
The strrpos() function finds the last occurrence of a string. You can use it to figure out where the file name starts.
$path = 'C:/dir/file.txt';
$pos = strrpos($path, '/');
$file = substr($path, $pos + 1);
echo $file;

Removing part of path in php

I have a path like:
$path='somefolder/foo/bar/lastdir';
and I want to remove the last part, so I have:
$path='somefolder/foo/bar';
Like I went one folder up.
I'm really newbie in php, maybe its just one function, although I can't find it anywhere.
You could try this (tested and works as expected):
$path = 'somefolder/foo/haha/lastone';
$parts = explode('/', $path);
array_pop($parts);
$newpath = implode('/', $parts);
$newpath would now contain somefolder/foo/haha.
use :
dirname(dirname('somefolder/foo/haha/lastone/somescript.php'));
this should return:
somefolder/foo/haha/
This is untested, but try:
$path_array = explode('/',$path);
array_pop($path_array);
$path = implode('/',$path_array);
If you are currently at:
somefolder/foo/haha/lastone/somescript.php
and you want to access:
somefolder/foo/haha/someotherscript.php
just type:
../someotherscript.php
Probably using a regex function would be appropriate if the last part is going to vary. Try
$pattern = '#/.*$#U';
$stripped_path = preg_replace($pattern, '', $original_path);
This will strip everything off the original path string starting from the last forward slash.
You could use a function that explodes() the $path variable into an array and then array_pop to get rid of the last element.
function path($path) {
$arrayPath = explode("/", $path);
$path = array_pop($arrayPath);
return $path = implode("/", $path);
}
The shortest variant in PHP is:
$path = preg_replace('|/[^/]*$|','', $path);
which uses a regular expression.

Replacing backslashes

I'm trying to replace / and \ with //:
$path = 'C:\wamp\www\mysite/bla/bla';
str_replace(array("\/", "\\"), array("\/\/", "\/\/"), $path);
but it doesn't work:(
I get C:\\/wamp\\/www\mysite/bla/bla ...
It is not necessary to escape the forward slash, so it is interfering with the pattern match.
Also, str_replace returns the replacement, it is not a byRef function so you'll need to store the return in a variable (docs).
See it happen: http://codepad.org/CNr8P79m
<?php
$path = 'C:\wamp\www\mysite/bla/bla';
$path = str_replace(array("/", "\\"), array("//", "//"), $path);
echo $path;
// output: C://wamp//www//mysite//bla//bla
?>
You don't need to escape / and you need to assign the return value of str_replace to a variable:
$path = str_replace(array("/", "\\"), array("//", "//"), $path);
If you're trying to normalize paths then I can recommend replacing all directory separators by / as this doesn't interfere with escaping and works on both Linux and Windows.
You don't need to escape slashes only backslashes.
$path = 'C:\wamp\www\mysite/bla/bla';
$path = str_replace(array('/', '\\'), array('//', '//'), $path);

remove characters from variable

$dir = '/web99/web/direcotry/filename';
I need to drop '/web99/web/' from the directory on the fly.
I tried:
$trimmed = ltrim($dir, "/web99/web/");
however if a directory started with a w,e,b,9 the first letter of the directory was cut off.
How can I drop only what I want and not every character like that?
$dir = preg_replace('$^/web99/web/$', '', $dir);
Use str_replace:
$dir = str_replace('/web99/web/', '', $dir);
You could just use str_replace if you know that it will never be anywhere else in the path:
$trimmed = str_replace('/web99/web/', '', $dir);
If you wanted to be really safe, you could use preg_replace to get the beginning of the string:
$trimmed = preg_replace('~^/web99/web/~', '', $dir);
I would use strtr(), so if you need other string replacements, editing will be easy :
$trimmed = strtr($dir, array('/web99/web/'=>''));

Categories