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!!
Related
I write a robot and fetch all URL in web page. the URLs is be like this:
http://www.example.com/result/رایانه
Now, When I try to fetch content of this url by CURL, give me this error:
400 Bad request
I know this cause because for "رایانه" in url and must encoding it.
But that URL is dynamically, and I need a solution for encode just params in URL.
Be like this:
"http://www.example.com/result/" . urlencode("رایانه")
Or another example:
Maybe I have this URL:
http://www.example.com/result/سوتی/?foo=علی&bar=حسن
If I use urlencode() return this:
http%3A%2F%2Fwww.example.com%2Fresult%2F%D8%B3%D9%88%D8%AA%DB%8C%2F%3Ffoo%3D%D8%B9%D9%84%DB%8C%26bar%3D%D8%AD%D8%B3%D9%86
But so must just encode this words: سوتی, علی, حسن.
and have this correct encoded:
http://www.example.com/result/%D8%B3%D9%88%D8%AA%DB%8C/?foo=%D8%B9%D9%84%DB%8C&bar=%D8%AD%D8%B3%D9%86
I need this for use in CURL.
How can I do this?
EDIT:
I found this code:
echo implode("/", array_map("urlencode", explode("/", $string)));
return:
http%3A//www.example.com/result/%D8%B3%D9%88%D8%AA%DB%8C/%3Ffoo%3D%D8%B9%D9%84%DB%8C%26bar%3D%D8%AD%D8%B3%D9%86
But the result is not exactly true.
I find a solution:
$string = 'http://www.example.com/result/سوتی/?foo=علی&bar=حسن';
$string = urlencode($string);
echo str_replace(array('%3A', '%2F', '%3F', '%3D', '%26'), array(':', '/', '?', '=', '&'), $string);
Output:
http://www.example.com/result/%D8%B3%D9%88%D8%AA%DB%8C/?foo=%D8%B9%D9%84%DB%8C&bar=%D8%AD%D8%B3%D9%86
It work with any URL and accept for use in CURL.
This is my code:
$produrl = '/'. basename(str_replace(".html","",$_cat->getUrl())) .'/' . basename($_product->getProductUrl()) ;
$_cat->getUrl() returns this:
http://website.com/category/subcategory.html
I need: for $produrl part of basename(str_replace(".html","",$_cat->getUrl()))to return category/subcategory
The issue:
It gives back only category without /subcategory I know the issue is in the str_replace it's wrong isn't? Can you help me with that?
Pleast Note I have 2 Cases:
Sometimes I get http://website.com/category/subcategory.html.
Sometimes http://website.com/category.html
And I would like it to work with both of them :)
You should use parse_url instead:
$url = parse_url($_cat->getUrl());
$produrl = str_replace(".html","",$url['path']);
The problem is that you're using the basename() function.
Take a look at the documentation for it: http://php.net/manual/en/function.basename.php
It will only return the trailing string after the "/" (forward slash) or "\" (back slash, for Windows).
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))
I am creating a site using CodeIgniter. I have an url like http://mysite.com/albums/MJ/Dangerous.html where MJ is the artist name and Dangerous is the name of the album. Both of these are dynamic and fetched from a database.
In the database there are some albums which have a slash ('/') character in them. So, such an URL becomes http://mysite.com/albums/50-cent/Get+Rich+or+Die+Tryin%27%2FThe+Massacre.html. On decoding, it turns out as http://ringtones/albums/50-cent/Get Rich or Die Tryin'/The Massacre.html. Here the artist is 50-cent and the album name is Get Rich or Die Tryin'/The Massacre
My question is, what do I do so that I get the entire album name, i.e. Get Rich or Die Tryin'/The Massacre.html as a single argument with the slash character? Currently CodeIgniter shows an error as "Page not found" when I click on such an URL. All other URL's which doesn't have the / works fine.
Try double URLencoding the album name (i.e. urlencode(urlencode($album))). I was trying to pass a URL once to a CodeIgniter controller and it constantly gave me troubles. So I just double encoded it, and then it popped through on the other side no problem. I then ran an urldecode() on the passed parameter.
Let me know if that helps you.
As per current SEO trend no need to bring the quote in url or to fetch on page.
instead during saving (in slag kind of field) and retrieving you can use this kind of option.
$base_url = "http://ringtones/";
$controller = "albums";
$artist = "50 cent";
$album = "Get Rich Or Die Tryin' / The Massacre";
$link1 = $base_url.$controller.'/'.url_title($artist,'-',TRUE).'/'.url_title($album,'-',TRUE);
echo $link1;
Result:
http://ringtones/albums/50-cent/get-rich-or-die-tryin-the-massacre
encode the value before passing
$value = str_replace('=', '-', str_replace('/', '_', base64_encode($album)));
decode the value after receiving
$value = base64_decode(str_replace('-', '=', str_replace('_', '/', $value)));
You will want to urlencode the album name when the data is retrieved from the model so that blackslash is escaped.
You need to use the HTML escaped version of the characters in your URL...
See below for a reference.
http://www.theukwebdesigncompany.com/articles/entity-escape-characters.php
After HTML encoding, your URL should look something like:
http://ringtones/albums/50-cent/Get Rich or Die Tryin'/The Massacre.html
I hope this helps!
N
Extending the #MikeMurko answer to include how to work with Javascript and PHP.
Simply go for double encoding and decoding;
JS:
var id = encodeURIComponent( encodeURIComponent('mystring/&-34') );
PHP:
$id = urldecode( urldecode('mystring/&-34') );
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?