Get a text block from a url - php

forexample, I have this url:
http://adstorage.jamba.net/storage/view/325/0/fa/Fairytale.mp3
How can I use PHP code so that it returns Fairytale. all the things before Fairytale and after that .mp3 should be removed.
the idetifier are / and .mp3 only the file name should be returned.

Use pathinfo() Function
<?php
$url = "http://example.com/file_name.mp3";
$f = pathinfo($url);
echo $f[filename]; // File name
?>

How about something like this:
$url = "http://adstorage.jamba.net/storage/view/325/0/fa/Fairytale.mp3";
$parts = parse_url($url);
$path_parts = explode('/', $parts['path']);
list($name, $extension) = explode(".", $path_parts[count($path_parts) - 1]);
echo $name;
This is probably overkill, and this thing could be done with a simple regex like:
preg_match("#.*/(\w+)\.\w+#", $url, $matches);
echo $matches[1];

Use pathinfo Function
<?php
$url = "http://adstorage.jamba.net/storage/view/325/0/fa/Fairytale.mp3";
$f = pathinfo($url);
echo $f[filename]; // File name Fairytale
print_r(pathinfo($url)); // File Array
?>

You can tryit with:
$input = 'http://adstorage.jamba.net/storage/view/325/0/fa/Fairytale.mp3';
echo current(explode('.', basename($input)));

Try in one line, $input being yout url (php 5.4) :
$name = explode('.',array_slice(explode('/',$input), -1, 1))[0];

Related

How do I use PHP Function preg_replace() in naming a .txt file after a site URL

How can I name a txt file after a site URL without the preceding https:// or http:// as in: www.google.com.txt?
I think I might be getting it wrong here: fopen($sitenameWithoutHTTP.".txt, "w");
Below is the way I'm trying to address that:
<?php
//
#mkdir("result", 0755);
#chdir("result");
$link = $sitename;
$sitename = preg_replace('#^https?://#', '', $sitenameWithoutHTTP);
$resultfile = fopen($sitenameWithoutHTTP.".txt", "w");
//
?>
Thanks for helping find a fix.
Hope this helps you achieve what you intended!
<?php
$siteName = 'https://www.google.com';
$siteNameWithoutHttps = preg_replace('#^https?://#', '', $siteName);
// print_r($siteNameWithoutHttps);
$resultFile = fopen($siteNameWithoutHttps.".txt", "w");
// run a check
if($resultFile == true) {
echo "success";
} else {
echo "failed";
}
The expected result for the commented print_r above should be:
www.google.com
$arr = ['http','https',':','/','?','&','#','.'];
$sitename = str_replace($arr, '', $sitenameWithoutHTTP);
also you can use base64_encode(), or use parse_url().
$HOST = parse_url($sitenameWithoutHTTP, PHP_URL_HOST);
and if you need to save real URL and get it again I see best way with using Md5 hash
$fileName = md5($sitenameWithoutHTTP).'.txt';
can get it again file.php/?getFile2url=[httpLink]
header('Location: '. Md5($_GET['getFile2url']).'.txt');
exit;

Remove all characters before last / in URL [duplicate]

This question already has answers here:
Get Last Part of URL PHP
(14 answers)
Closed 7 years ago.
I need to remove every characters before the last "/"
This my url :
http://www.example.com/highlights/cat/all-about-clothing/
And I want to have only :
all-about-clothing
Thanks
Use basename()
$str = 'http://www.example.com/highlights/cat/all-about-clothing/';
echo basename($str);
// Outputs: all-about-clothing
EDIT:
Another Solution:
$str = 'http://www.example.com/highlights/cat/all-about-clothing/';
$path = pathinfo($str, PATHINFO_BASENAME);
echo "<br/>" . $path;
Use PHP's parse_url() function.
edit:
basename() or pathinfo() is the easier way.
$str = 'http://www.example.com/highlights/cat/all-about-clothing/';
$str = trim($str,'/');
$str = explode('/',$str);
echo $str = end($str);
// get result
all-about-clothing
<?php
$url = "http://www.example.com/highlights/cat/all-about-clothing/";
$url_path = parse_url($url, PHP_URL_PATH);
$basename = pathinfo($url_path, PATHINFO_BASENAME);
echo $basename;
?>
You can use regex too:
$match = [];
$subject = 'http://www.example.com/highlights/cat/all-about-clothing/';
$pattern = '/http:\/\/www\.example\.com\/highlights\/cat\/(.*)/';
preg_match($pattern, $subject, $match);
print_r($match);
You can see the result here.
<?php
$url = 'http://www.example.com/highlights/cat/all-about-clothing/';
$basename = split('/',$url);
echo $basename[5];
?>
Most of the above solution focus on the exact example URL,
Please be careful as if extra params are added to the end of the string,
you may get the wrong result:
http://www.example.com/highlights/cat/all-about-clothing/?page=1
http://www.example.com/highlights/cat/all-about-clothing/item/1
to cache the 3rd "directory" after the domain name, and ignore the rest of the URL, the following code can be used:
$url = "http://www.example.com/highlights/cat/all-about-clothing/item/1";
$url_path = parse_url($url, PHP_URL_PATH); # /highlights/cat/all-about-clothing/item/1
$dirs = explode('/', $url_path); # Array([0] =>"", [1]=>"highlights", [2]=>"cat", [3]=>"all-about-clothing", [4]=>"item", [5]=>"1")
echo $dirs[3]; # all-about-clothing

Get the first directory from URL with PHP

I have url in variable like this:
$url = 'http://mydomain.com/yep/2014-04-01/some-title';
Then what I want is to to parse the 'yep' part from it. I try it like this:
$url_folder = strpos(substr($url,1), "/"));
But it returns some number for some reason. What I do wrong?
Use explode, Try this:
$url = 'http://mydomain.com/yep/2014-04-01/some-title';
$urlParts = explode('/', str_ireplace(array('http://', 'https://'), '', $url));
echo $urlParts[1];
Demo Link
Well, first of all the substr(...,1) will return to you everthing after position 1. So that's not what you want to do.
So http://mydomain.com/yep/2014-04-01/some-title becomes ttp://mydomain.com/yep/2014-04-01/some-title
Then you are doing strpos on everthing after position 1 , looking for the first / ... (Which will be the first / in ttp://mydomain.com/yep/2014-04-01/some-title). The function strpos() will return you the position (number) of it. So it is returning you the number 4.
Rather you use explode():
$parts = explode('/', $url);
echo $parts[3]; // yep
// $parts[0] = "http:"
// $parts[1] = ""
// $parts[2] = "mydomain.com"
// $parts[3] = "yep"
// $parts[4] = "2014-04-01"
// $parts[4] = "some-title"
The most efficient solution is the strtok function:
strtok($path, '/')
So complete code would be :
$dir = strtok(parse_url($url, PHP_URL_PATH), '/')
Use parse_url function.
$url = 'http://mydomain.com/yep/2014-04-01/some-title';
$url_array = parse_url($url);
preg_match('#/(?<path>[^/]+)#', $url_array['path'], $m);
$url_folder = $m['path'];
echo $url_folder;

Get the filename part from a given URL

I have a URL like below:
http://abc.def.com/gh-tqa/name-of-the-file/ZW607CCF.html
Now I want to get the string of ZW607CCF without .html.
How can I achieve this using PHP?
You don't need a regex here. Just use pathinfo():
$url = 'http://abc.def.com/gh-tqa/name-of-the-file/ZW607CCF.html';
$filename = pathinfo($url, PATHINFO_FILENAME);
There are lot of ways in PHP, try preg_replace(), for example:
$url = 'http://abc.def.com/gh-tqa/name-of-the-file/ZW607CCF.html';
$value = preg_replace("|.*/([^.]+)\.html|", "$1", $url);
this is how you do:
$temp = explode('.', $_SERVER['PHP_SELF']);
$string = $temp[0];
with PHP 5.4+ you can also do:
$string = explode('.', $_SERVER['PHP_SELF'])[0];

URL - Get last part in PHP

I have my url:
http://domain/fotografo/admin/gallery_bg.php
and i want last part of the url:
gallery_bg.php
but, I do not want to link static, ie, for each page that vistitar I want to get the last part of the url
use following
<?php
$link = $_SERVER['PHP_SELF'];
$link_array = explode('/',$link);
echo $page = end($link_array);
?>
Use basename function
echo basename("http://domain/fotografo/admin/gallery_bg.php");
If it is same page:
echo $_SERVER["REQUEST_URI"];
or
echo $_SERVER["SCRIPT_NAME"];
or
echo $_SERVER["PHP_SELF"];
In each case a back slash(/gallery_bg.php) will appear. You can trim it as
echo trim($_SERVER["REQUEST_URI"],"/");
or split the url by / to make an array and get the last item from array
$array = explode("/",$url);
$last_item_index = count($url) - 1;
echo $array[$last_item_index];
or
echo basename($url);
$url = "http://domain/fotografo/admin/gallery_bg.php";
$keys = parse_url($url); // parse the url
$path = explode("/", $keys['path']); // splitting the path
$last = end($path); // get the value of the last element
you can use basename($url) function as suggested above. This returns the file name from the url. You can also provide the file extension as second argument to this function like basename($url, '.jpg'), then the filename without the extension will be served.
Eg:
$url = "https://i0.com/images/test.jpg"
then echo basename($url) will print test.jpg
and echo basename($url,".jpg") will print test
$url = $_SERVER["PHP_SELF"];
$path = explode("/", $url);
$last = end($path);
Try this:
Here you have 2 options.
1. Using explode function.
$filename = end(explode('/', 'http://domain/fotografo/admin/gallery_bg.php'));
2. Use basename function.
$filename = basename("http://domain/fotografo/admin/gallery_bg.php");
-
Thanks
$basepath = implode('/', array_slice(explode('/', $_SERVER['SCRIPT_NAME']), 0, -1)) . '/';
$uri = substr($_SERVER['REQUEST_URI'], strlen($basepath));
if (strstr($uri, '?')) $uri = substr($uri, 0, strpos($uri, '?'));
$url = trim($uri, '/');
In PHP 7 the accepted solution is giving me the error that only variables are allowed in explode so this works for me.

Categories