Remove root directory from a directory path string - PHP - php

I have a variable like $path = "dir1/dir2/dir1/dir4/"; etc.. etc..
I want to remove the first member dir1/ and want result like dir2/dir1/dir4/.
I think it is possible by making the variable an array by explode('/', $path). How can I remove the first member vrom array and reconstruct that array into a text variable??
How can I achieve this in PHP?

According to your updated question
Only explode into two parts, take the second one. In case the second one does not exists, give it NULL:
list(, $result) = explode("/", $path, 2) + array( 1 => NULL);
OR
$array = explode("/", $path);
unset($array[0]);
echo $text = implode("/", $array);

preg_replace('~^[^/]+/~', '', $path);
or if you don't want regexp:
substr($path, strpos($path, '/') + 1);

$result = explode("/", $path); // Pull it apart
array_shift($result); // Pop the first index off array
$result = implode("/", $result); // Put it together again

You can do like that
$result= explode("/", $path);.
You will get result as an array.

Related

How can I get the end of a string in PHP?

Substr PHP
I have a string like http://domain.sf/app_local.php/foo/bar/33.
The last characters are the id of an element. Its length could be more than one, so I can not use:
substr($dynamicstring, -1);
In this case, it must be:
substr($dynamicstring, -2);
How can I get the characters after "/bar/" on the string without depending on the length?
To ensure you are getting an immediate section after the bar, use regular expressions:
preg_match('~/bar/([^/?&#]+)~', $url, $matches);
echo $matches[1]; // 33
You can use explode(), like this:
$id = explode('/',$var);
And take the element where you had the id.
You could use explode('/', $dynamicstring) to split the string into an array of the strings inbetween each /. Then you could use end() on the result of this to get the last part.
$id = end(explode('/', $dynamicstring));
Try this:
$dynamicstring = 'http://domain.sf/app_local.php/foo/bar/33';
// split your string into an array with /
$parts = explode('/', $dynamicstring);
// move the array pointer to the end
end($parts);
// return the current position/value of the $parts array
$id = current($parts);
// reset the array pointer to the beginning => 0
// if you want to do any further handling
reset($parts);
echo $id;
// $id => 33
Test it yourself here.
You can use a regular expression to do it:
$dynamicstring = "http://domain.sf/app_local.php/foo/bar/33";
if (preg_match('#/([0-9]+)$#', $dynamicstring, $m)) {
echo $m[1];
}
I tested it out myself before answering. Other answers are reasonable too, but this will work according to your need...
<?php
$url = "http://domain.sf/app_local.php/foo/bar/33";
$id = substr($url, strpos($url, "/bar/") + 5);
echo $id;
Please find the below answer.
$str = "http://domain.sf/app_local.php/foo/bar/33";
$splitArr = explode('/', explode('//', $str)[1]);
var_dump($splitArr[count($splitArr)-1]);

Create an Array and get Element, or part of String, in One Line - PHP

To create an array from a string and get an element you need to do this:
$string = "1/2";
$array = explode("/", $string);
$elem = $array[0];
A little trick lets you use the strstr() and provides the same result as both lines above.
$elem = strstr($string, "/", true);
The issue is..
What if you want to return after the "/" instead of before it, but without the "/" prepended
If the "/" does not exist in the array, false is returned
strstr() is not the answer. Is there another method or syntax to get the string before the "/" in one line either by doing an array operation or some string operation?
You can do it like this in php 5.4 +
$string = "1/2";
$first = explode("/", $string)[0];
Eval.in example
You can use substr():
$after = substr($string, strpos($string, '/')+1);
the +1 makes it skip past the /.

split a link with php / preg_split

i have a link with the following (varying) structure:
http://website.com/category/product/abc12345
the category- and the productname vary concerning their length, but the id (abc12345) is always located after the last "/" and is about 6-8 chars long.
i tried to extract the link with the following code:
preg_split('/[/]/', $val, $arr);
$narr[] = end($arr);
with val being the link and arr being the array, the result should be pasted in.
narr is the array i want to save to a file later, so it doesn't really matter here. unfortunately, my results are always empty when i try it this way.
I would go for:
$urlParts = parse_url($myUrl);
$parts = explode('/', $urlParts['path']);
$productId = array_pop($parts);
That way, you have no problems with anchors (#content) or query parameters (?id=123)
I'd use preg_match:
if (preg_match('#.*/(.*)#', $val, $match)) {
$result = $match[1];
}
You could also use something as simple as strrpos and substr:
$result = substr($val, strrpos($val, '/') + 1);
Under the following conditions:
The product (abc12345) is always at the end of the url
No querystrings/params
Try the following regular expression:
preg_match('/\/([\w]+)\/?$/', $val, $arr);
$product = $arr[1];

Need to get middle part of path

I have a path like this
apples/oranges/bananas
I need to get the middle item in the path, in this case oranges.
What is the best way to do it? I can do it myself using strpos and substr but I imagine there is a better way...
$path = explode("/", "apples/oranges/bananas");
echo $path[1];
You could explode the string (assuming it is) and then get the correct index from the array. Like so:
$string = "apples/oranges/bananas";
$array = explode('/', $string);
echo $array[1]; //outputs oranges
Just to show off array dereferencing in PHP > 5.4:
echo explode('/', 'apple/oranges/bananas')[1];
If
$path = 'apples/oranges/bananas';
you could do:
$dir = basename(dirname($path));
if you want to start from the end of the string, and should work on Windows, or
$dir = preg_match('|/([^/]*)|', $path, $m) ? $m[1] : false;
if you want to start at the beginning of the string, and will not work on Windows.
Is it always 3 words separated by 2 slashes?
if yes, you can try:
$mypath = explode('/', 'apple/oranges/bananas');
echo $mypath[1]; //gives oranges

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.

Categories