I am wondering how I can parse this string to get a certain name or string. What I need to parse is:
items/category/test.txt
To get it with out test.txt
of course there will be different names so I can't just replace it.
I need the result to be:
items/category/
Also how can I parse it to get /category/
only?
Use PHP's pathinfo()
function:
http://php.net/manual/en/function.pathinfo.php
$info = pathinfo('items/category/test.txt');
$dirPath = $info['dirname'];
// OR
$dirPath = pathinfo('items/category/test.txt', PATHINFO_DIRNAME);
// Output: items/category
Use explode to get the above string as array
$string = "tems/category/test.txt";
$string_array = explode("/",$string);
print_r($string_array); // Will Output above as an array
// to get items/category/
$var = $string_array[0].'/'.$string_array[1];
echo $var; //will output as items/category/
$var2 = '/'.$string_array[1].'/';
echo $var2; //will output as /category/
I believe your best chance is explode("/","items/category/test.txt")
. This will splice the string every time it finds / returning an array, whereas implode
(join
is an alias of it) will join an array of strings, so
$spli=explode("/","items/category/test.txt");
implode($spli[0],$spli[1]);
Should do the trick for the first case, returning items/category
For category
alone, $spli[1]
is enough.
Of course, you may pass the string as a variable, for instance$foo="items/category/test.txt;" explode("/",$foo);
etc.