basic question in foreach in php - php

basically if I have a string like this:
$str = \data1\data2\data3\data_tmp\file.pgp
can anyone tell me how to get the last part 'file.pgp'?
TIA.

You are looking for the basename() function.
This function takes a file path and returns the file name without the suffix (the final part of your file name that specifies its type)

$last = array_pop(explode('\\', $str));
You don't need foreach for that. It's used when you have to iterate through the whole collection (in your case, array).
If you need to get the remaining part of the string:
$segments = explode('\\', $str);
$last = array_pop($segments);
It will be in $segments, as an array. If you want to convert it back to a string, then use join('\\', $segments). However, if this is a Windows path and you're running PHP on Windows, then you should be using the basename and dirname functions.

perhaps pathinfo() will give you what you need
if that doesn't do it try
$path = str_replace('\\', '/', $path)
first

Related

How to convert this url to %20?

A very simple problem which might have been solved here a lot of time, but I'm not getting what I want.
I have an image url like this:
$image = 'http://perfumepalace.arctechsolution.com/image/cache/data/another/For Her/Believe 100ml EDP-150x150.jpg';
and want output in this form
http://perfumepalace.arctechsolution.com/image/cache/data/another/For%20Her/Believe%20100ml%20EDP-150x150.jpg
Yes ofcourse you will tell me I can use urlencode or rawurlencode. Believe me I've tried and still no luck.
With urlencode I get like this
http%3A%2F%2Fperfumepalace.arctechsolution.com%2Fimage%2Fcache%2Fdata%2Fanother%2FFor+Her%2FBelieve+100ml+EDP-150x150.jpg
And with rawurlencode I received output like this:
http%3A%2F%2Fperfumepalace.arctechsolution.com%2Fimage%2Fcache%2Fdata%2Fanother%2FFor%20Her%2FBelieve%20100ml%20EDP-150x150.jpg
With str_replace I can get exactly what I want like this:
str_replace('+', '%20', $image);
will result: http://perfumepalace.arctechsolution.com/image/cache/data/another/For%20Her/Believe%20100ml%20EDP-150x150.jpg
but I want to get them using urlencode or rawurlencode. But these functions encode even slash / part as well.
Is there any way to url encode only spaces in the url?
Edit: Yes i can use basename() or pathinfo to encode only part of the url. But the directory name might also contain the space character, so converting only filename is also not a possibility here.
And actually I want to know if we can use urlencode, or rawurlencode in full url without affecting the '/' of the fullurl. I don't want the regex suggestions eigher.
Note: The complication part is that 'For Her' directory section in the url path, and the level of directory is also not fixed.
What you need is rawurlencode(), but only encode the necessary part of your url.
Example:
$image = sprintf(
'http://perfumepalace.arctechsolution.com/image/cache/data/another/%s/%s',
rawurlencode('For Her'),
rawurlencode('Believe 100ml EDP-150x150.jpg')
);
But if you still want to apply to the whole url string, you could do like below:
function my_url_encode($url) {
$info = parse_url($url);
return sprintf('%s://%s/%s',
$info['scheme'],
$info['host'],
implode('/', array_map('rawurlencode', explode('/', $info['path']))));
}
UrlEncode should be used only when encoding a string to be used in query of the url.
So my suggestion here is for you to keep with the str_replace('+', '%20', $image); code, as you have the full url and not only the query part.
The other option is to parse the url, extract the path, encode it and rebuild the url, here is one example:
$image = 'http://perfumepalace.arctechsolution.com/image/cache/data/another/For Her/Believe 100ml EDP-150x150.jpg'
$path = parse_url($image, PHP_URL_PATH);//extract the path
$epath = rawurlencode($path);//encode it
$enc_image = 'http://perfumepalace.arctechsolution.com/'.$epath;//build the new url
Try this:
$image = 'http://perfumepalace.arctechsolution.com/image/cache/data/another/For Her/Believe 100ml EDP-150x150.jpg';
$parts = parse_url($image);
$image_path = explode('/',$parts['path']);
foreach($image_path as $key => $image_path_part){
$image_path[$key] = rawurlencode($image_path_part);
}
echo $parts['scheme']."://".$parts['host'].implode('/',$image_path);
Output: http://perfumepalace.arctechsolution.com/image/cache/data/another/For%20Her/Believe%20100ml%20EDP-150x150.jpg
Have a nice day!!

Retrieve and tidy up one directory name in a url. e.g. I need example.com/main/this_dir/page.html to output as "This Dir"

I am stuggling to comprehend how to accomplish the following task "
From : http://www.example.com/main/this_dir/page.html
I would like an output of : This Dir
When using $_SERVER['REQUEST_URI'] i can get this output :
*/main/this_dir/*
I would like to now take that and strip the last string between the two /'s so i end up with
*this_dir*
I would then like to take that string and turn it into
This Dir
There is a slight complication with this too because the directory could simply be called /this/ and not /this_dir/, but it is always one or the other and the text does change whereas the words i used were merely an example.
If anyone has any suggestions, input or feedback as to how i could accomplish this task it would be greatly appreciated! I do have a vague idea of how i could strip the last directory name from the request_uri string but i would really like to know if it would even be possible to transform the string in the way that i have described, using PHP.
You can use the basename function to get the "this_dir" part, so then it's simply a case of doing something like this:
$directoryName = ucwords(str_replace('_', ' ', basename($_SERVER['REQUEST_URI'])));
Edit
Slightly more convoluted example that will work for pages such as "/main/this_dir/something.php":
$directoryName = ucwords(str_replace('_', ' ', basename(substr($_SERVER['REQUEST_URI'], 0, strrpos($_SERVER['REQUEST_URI'], '/')))));
This is just stripping anything after the final "/" before passing to basename to ensure it'll work as before. Note that this will NOT work though for URLs without a trailing "/" such as "/main/this_dir" - in this case it would output "Main".
$path = explode("/", dirname($_SERVER['REQUEST_URI']));
$directory = end($path);
This should give you the last directory in the path.
Then you can do:
$dirParts = explode("_", $directory);
$dirName = implode(" ", array_map("ucfirst", $dirParts));
To get the directory name in a user-friendly format.
Edit: In fact, as RobMaster said, it is probably easier to do ucwords(str_replace("_", " ", $directory))

PHP: Get last directory name from path

I am writing one function for getting some different database query. Now things are going well but only need to get last directory name from defined path.
$qa_path=site_root('/learnphp/docs/');
I wan to get only docs from above path. Here site_root is nothing but $_SERVER['DOCUMENT_ROOT'] So how can I get only docs ?
Thanks
Easiest way would be to use basename($yourpath) as you can see here: http://php.net/basename
Provided answer doesn't work if your string contains the file at the end, like :
basename('/home/mypath/test.zip');
gives
test.zip
So if your string contains the file, don't forget to dirname it first
basename(dirname('/home/mypath/test.zip'));
gives
mypath
This is the easiest way:
<?php
echo basename(getcwd());
?>
getcwd() = give your full directory path
basename() = give you last directory
Try explode('/', '/learnphp/docs/')
to split the string into array locations. Then fetch the last location.
Here is more info:
http://php.net/manual/en/function.explode.php
you can use this simple snippet:
$qa_path=site_root('/learnphp/docs/');
$qa_path = explode("/", $qa_path);
$qa_path = $qa_path[count($qa_path) - 1];
$qa_path=explode('/', '/learnphp/docs/');
echo $qa_path[2]; // output docs
This will help you
$qa_path=site_root('/learnphp/docs/');
$q_path = explode ("/", $qa_path);
$lastV = end($q_path);
This gives you the current directory name:
echo basename(dirname(__FILE__));

Edit filepath PHP

I have a delete button on my page, that delete button has to delete a certain entry in my database (not too difficult), it has to delete the entire folder where the file that holds the delete button is in (also doable), but I also want it to delete another folder that's placed somewhere else and I'm not sure how to do that. Using
dirname(__FILE__);
I am able to get the filepath where the file holding the delete button is located. That results in this:
mywebsite.nl/subdomains/dongen/httpdocs/s-gravenmoer/aandrijvingenenbesturingen/logo4life
The filepath that I also want to delete is quite similair, but a little different. The last 3 folders a variable, so their lenght (in characters) is always different. However, the second to last folder has to be deleted from this filepath so this remains:
mywebsite.nl/subdomains/dongen/httpdocs/s-gravenmoer/logo4life
Is there a way to do this with PHP? Using substr or something like that perhaps?
Thanks!
I think this should do the trick:
$folderToRemove = preg_replace( '#^(.*)/(.*?)/(.*?)$#', "$1/$3", dirname(__FILE__) );
You can try using "glob." Details in www.php.net/glob
You can try:
$files = glob('subdomains/dongen/httpdocs/*/logo4life');
foreach ($files as $file) {
unlink($file); // note that this is very dangerous though, you may end up deleting a lot of files
}
You don't need anything fancy, as you guessed, a simple str_replace will do it:-
$file = 'mywebsite.nl/subdomains/dongen/httpdocs/s-gravenmoer/aandrijvingenenbesturingen/logo4life';
var_dump(str_replace('aandrijvingenenbesturingen/', '', $file));
Output:-
string 'mywebsite.nl/subdomains/dongen/httpdocs/s-gravenmoer/logo4life' (length=62)
$path = "mywebsite.nl/subdomains/dongen/httpdocs/s-gravenmoer/aandrijvingenenbesturingen/logo4life";
$regex = "/(.*\/).*\/(.*)/";
$matches = array();
preg_match($regex, $path, $matches);
// var_dump($matches);
$new_path = $matches[1].$matches[2];
echo $new_path;
Above code uses preg_match for matching a regexp in a string.

regexp get filename from url

url: http://blabla.bl/blabla/ss/sd/filename
How to get a filename?
http://us2.php.net/manual/en/function.basename.php
It works even on urls.
Use earcar's suggestion (basename) to get the filename.
BUT, if we're starting with a URL and the filename includes a query string, use Mauris's suggestion as well.
The query string will start with ? (that's how we know it's not part of the filename) and we can use
explode('?', basename($url));
This is summed up by the online PHP manual for basename
Given an arbitrary URL, I think you should use basename() together with parse_url(). Something like this:
$parsed_url = parse_url($url);
$path = $parsed_url['path'];
$filename = basename($path);
Yes it works, but last thing, sometimes basename is aaaa_somewhat. How to delete _somewhat?

Categories