I want to get out of the URL after the last slash "/" the text. The page URL is very variable, for example:
http://mydomain.com/colors/productname.html
(result is "productname") OK!
http://mydomain.com/colors/size/zip/shipment/
(result is "shipment") OK!
or
http://mydomain.com/colors/
(result is "null") Null!
It works well so far except for the last example. Once, just a slash "/" after the domain name is I get no result.
What is my mistake?
Thanks in advance!
$url = "variable"
if (strpos($url,'.h') !== false) {
$url = preg_replace('/\.h.*/', '/', $url);}
$url = rtrim($url, "/");
$str = substr(strrchr($url, '/'), 1);
$str = str_replace('-',' ',$str);
$keys = str_replace('/ /', '%20', $str);
$metric = urlencode($keys);
php already has a function that does this its called basename
$url = "http://mydomain.com/colors/";
echo basename($url);
//outputs
colors
$url = "http://mydomain.com/colors/productname.html";
echo basename($url);
//outputs
productname.html
What is stopping you from using basename?
<?php
$url = "http://mydomain.com/colors/";
$url = basename( $url ); //outputs "colors"
echo $url;
?>
Or if you dont want the ".html" in output, you can use pathinfo with PATHINFO_FILENAME flag
<?php
$url = "http://mydomain.com/colors.html";
$url = pathinfo( $url, PATHINFO_FILENAME ); //also outputs "colors"
echo $url;
?>
Related
I have to extract a specific part of an URL.
Example
original URLs
http://www.example.com/PARTiNEED/some/other/stuff
http://www.example.com/PARTiNEED
in case 1 I need to extract
/PARTiNEED/
and in case 2 I need to extract the same part but add an additional "/" at the end
/PARTiNEED/
What I've got right now is this
$tempURL = 'http://'. $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
$tempURL = explode('/', $tempURL);
$tempURL = "/" . $tempURL[3] . "/";
is there a more convenient way to do this or is this solution fine?
It's normally a good idea to use PHP's built in functions for things like this where possible. In this case, the parse_url method is designed for parsing URLs.
In your case:
// Extract the path from the URL
$path = parse_url($url, PHP_URL_PATH);
// Separate by forward slashes
$parts = explode('/', $path);
// The part you want is index 1 - the first is an empty string
$result = "/{$parts[1]}/";
You don't need this part:
'http://'. $_SERVER['SERVER_NAME']
you can just do:
$tempURL = explode('/', $_SERVER['REQUEST_URI']);
$tempURL = "/" . $tempURL[1] . "/";
Edited index from 0 to 1 as commented.
Maybe regex suits your needs better?
$tempURL = "http://www.example.com/PARTiNEED/some/other/stuff"; // or $tempURL = "http://www.example.com/PARTiNEED
$pattern = '#(?<=\.com)(.+?)(?=/|$)#';
preg_match($pattern, $tempURL, $match);
$result = $match[0] . "/";
Here this should solve your problem
// check if the var $_SERVER['REQUEST_URI'] is set
if(isset($_SERVER['REQUEST_URI'])) {
// explode by /
$tempURL = explode('/', $_SERVER['REQUEST_URI']);
// what you need in in the array $tempURL;
$WhatUNeed = $tempURL[1];
} else {
$WhatUNeed = '/';
}
Dont worry about the trailing slash, that can be added anytime in your code.
$WhatUNeed = $tempURL[1].'/';
This will give you proper idea about your requirment.
<?php
$url_array = parse_url("http://www.example.com/PARTiNEED/some/other/stuff");
$path = $url_array['path'];
var_dump($path);
?>
now you can use string explode function to get your job done.
Sorry, I'm bad English. I'm going to post my code now:
$image = 'http://example.com/thisisimage.gif';
$filename = substr($image, strrpos($image, '/') + 1);
echo '<br>';
echo $filename;
echo '<br>';
echo preg_replace('/^[^\/]+/', 'http://mydomain.com', $image);
echo '<br>';
$image is string;
$filename is image name (in example above, it returns 'thisisimage.gif')
Now i want replace all before $filename with 'http://mydomain.com', my code is above but it doesnt work.
Thanks!
$foo = explode($filename, $image);
echo $foo[0];
Explode "splits" one the given paramater ( in your case $filename ). It returns an array with where the keys are split on the string you gave.
And if you just want to change the url. you use a str_replace
$foo = str_replace("http://example.com", "http://localhost", $image);
//This will change "http://example.com" to "http://localhost", like a text replace in notepad.
In your case:
$image = 'http://example.com/thisisimage.gif';
$filename = substr($image, strrpos($image, '/') + 1);
$foo = explode($filename, $image);
echo '<br>';
echo $filename;
echo '<br>';
echo str_replace($foo[0], "http://yourdomain.com/", $url);
echo '<br>';
There's another approach in which you don't need a regular expression:
in Short:
$image = 'http://example.com/thisisimage.gif';
$url = "http://mydomain.com/".basename($image);
Explanation:
If you just want the file name without url's or directory path's, basename() is your friend;
$image = 'http://example.com/thisisimage.gif';
$filename = basename($image);
output: thisisimage.gif
Then you can add whatever domain you want:
$mydomain = "http://mydomain.com/";
$url = $mydomain.$filename;
Try this :
$image = 'http://example.com/thisisimage.gif';
echo preg_replace('/^http:\/\/.*\.com/', 'http://mydomain.com',$image);
This should simply work:
$image = 'http://example.com/thisisimage.gif';
$filename = substr($image, strrpos($image, '/') + 1);
echo '<br>';
echo $filename;
echo '<br>';
echo 'http://mydomain.com/'.$filename;
echo '<br>';
if you just like to add your own domain before the file name, try this:
$filename = array_pop(explode("/", $image));
echo "http://mydomain.com/" . $filename;
if you wanna only replace thedomain, try this:
echo preg_replace('/.*?[^\/]\/(?!\/)/', 'http://mydomain.com/', $image);
The other people here have given good answers about how to do it - regex has its advantages but also drawbacks - its slower, respectively requires more resources and for something simple as this, I would advice you to use the explode approach, but while speaking for regex functions you also may try this, instead your preg_replace:
echo preg_replace('#(?:.*?)/([^/]+)$#i', 'http://localhost/$1', $image);
It seems variable length positve lookbehind is not supported in PHP.
I have a filename with a date in it, the date is always at the end of the filename.
And there is no extension (because of the basename function i use).
What i have:
$file = '../file_2012-01-02.txt';
$file = basename('$file', '.txt');
$date = preg_replace('PATTERN', '', $file);
Im really not good at regex, so could someone help me with getting the date out of the filename.
Thanks
I suggest to use preg_match instead of preg_replace:
$file = '../file_2012-01-02';
preg_match("/.*([0-9]{4}-[0-9]{2}-[0-9]{2}).*/", $file, $matches);
echo $matches[1]; // contains '2012-01-02'
If there is always an underscore before the date:
ltrim(strrchr($file, '_'), '_');
^^^^^^^ get the last underscore of the string and the rest of the string after it
^^^^^ remove the underscore
I suggest you to try:
$exploded = explode("_", $filename);
echo $exploded[1] . '<br />'; //prints out 2012-01-02.txt
$exploded_again = explode(".", $exploded[1]);
echo $exploded_again[0]; //prints out 2012-01-02
Shorten it:
$exploded = explode( "_" , str_replace( ".txt", "", $filename ) );
echo $exploded[1];
With this, use regexp when you really need to :
current(explode('.', end(explode('_', $filename))));
This should help i think:
<?php
$file = '../file_2012-01-02.txt';
$file = basename("$file", '.txt');
$date = preg_replace('/(\d{4})-(\d{2})-(\d{2})$/', '', $file);
echo $date; // will output: file_
?>
I need to remove www from the string given by $_SERVER['HTTP_HOST']
How can I do that in PHP?
$server_name = str_replace("www.", "", $_SERVER['HTTP_HOST']);
That should do the trick...
if (substr($_SERVER['HTTP_HOST'], 0, 4) == 'www.') {
$domain = substr($_SERVER['HTTP_HOST'], 4);
} else {
$domain = $_SERVER['HTTP_HOST'];
}
Client requested site name "www.example.com"
// explode the string at the '.' and inserts into an array
$pieces = explode(".", $_SERVER['HTTP_HOST']);
// $pieces array is now:
// now $pieces[0] contains "www"
// now $pieces[1] contains "example"
// now $pieces[2] contains "com"
// Put the domain name back together using concatenation operator ('.')
$DomainNameWithoutHostPortion = $pieces[1].'.'.$pieces[2];
// now $DomainNameWithoutHostPortion contains "example.com"
Instead of str_replace, you could use ltrim:
$sender_domain = $_SERVER[HTTP_HOST];
$sender_domain = ltrim($sender_domain, 'www.');
Do you want this:
$_SERVER['HTTP_HOST'] = str_replace('www.', '',$_SERVER['HTTP_HOST']);
Here
$host = str_replace('www.', null, $_SERVER['HTTP_HOST'])
You can also
$ht = "http://";
$host = str_replace('www.',$ht, $_SERVER['HTTP_HOST'])
This is the url of my script: localhost/do/index.php
I want a variable or a function that returns localhost/do (something like $_SERVER['SERVER_NAME'].'/do')
$_SERVER['SERVER_NAME'] . dirname($_SERVER['REQUEST_URI']);
Try:
$url = $_SERVER['REQUEST_URI']; //returns the current URL
$parts = explode('/',$url);
print_r($parts);
EDIT:
$url = $_SERVER['REQUEST_URI']; //returns the current URL
$parts = explode('/',$url);
$dir = $_SERVER['SERVER_NAME'];
for ($i = 0; $i < count($parts) - 1; $i++) {
$dir .= $parts[$i] . "/";
}
echo $dir;
This should return localhost/do/
I suggest not to use dirname(). I had several issues with multiple slashes and unexpected results at all. That was the reason why I created currentdir():
function currentdir($url) {
// note: anything without a scheme ("example.com", "example.com:80/", etc.) is a folder
// remove query (protection against "?url=http://example.com/")
if ($first_query = strpos($url, '?')) $url = substr($url, 0, $first_query);
// remove fragment (protection against "#http://example.com/")
if ($first_fragment = strpos($url, '#')) $url = substr($url, 0, $first_fragment);
// folder only
$last_slash = strrpos($url, '/');
if (!$last_slash) {
return '/';
}
// add ending slash to "http://example.com"
if (($first_colon = strpos($url, '://')) !== false && $first_colon + 2 == $last_slash) {
return $url . '/';
}
return substr($url, 0, $last_slash + 1);
}
Why you should not use dirname()
Assume you have image.jpg located in images/ and you have the following code:
<img src="<?php echo $url; ?>../image.jpg" />
Now assume that $url could contain different values:
http://example.com/index.php
http://example.com/images/
http://example.com/images//
http://example.com/
etc.
Whatever it contains, we need the current directory to produce a working deeplink. You try dirname() and face the following problems:
1.) Different results for files and directories
File
dirname('http://example.com/images/index.php') returns http://example.com/images
Directory
dirname('http://example.com/images/') returns http://example.com
But no problem. We could cover this by a trick:
dirname('http://example.com/images/' . '&') . '/'returns http://example.com/images/
Now dirname() returns in both cases the needed current directory. But we will have other problems:
2.) Some multiple slashes will be removed
dirname('http://example.com//images//index.php') returns http://example.com//images
Of course this URL is not well formed, but multiple slashes happen and we need to act like browsers as webmasters use them to verify their output. And maybe you wonder, but the first three images of the following example are all loaded.
<img src="http://example.com/images//../image.jpg" />
<img src="http://example.com/images//image.jpg" />
<img src="http://example.com/images/image.jpg" />
<img src="http://example.com/images/../image.jpg" />
Thats the reason why you should keep multiple slashes. Because dirname() removes only some multiple slashes I opened a bug ticket.
3.) Root URL does not return root directory
dirname('http://example.com') returns http:
dirname('http://example.com/') returns http:
4.) Root directory returns relative path
dirname('foo/bar') returns .
I would expect /.
5.) Wrong encoded URLs
dirname('foo/bar?url=http://example.com') returns foo/bar?url=http:
All test results:
http://www.programmierer-forum.de/aktuelles-verzeichnis-alternative-zu-dirname-t350590.htm#4329444
php has many functions for string parsing which can be done with simple one-line snippets
dirname() (which you asked for) and parse_url() (which you need) are among them
<?php
echo "Request uri is: ".$_SERVER['REQUEST_URI'];
echo "<br>";
$curdir = dirname($_SERVER['REQUEST_URI'])."/";
echo "Current dir is: ".$curdir;
echo "<br>";
address bar in browser is
http://localhost/do/index.php
output is
Request uri is: /do/index.php
Current dir is: /do/
When I was implementing some of these answers I hit a few problems as I'm using IIS and I also wanted a fully qualified URL with the protocol as well. I used PHP_SELF instead of REQUEST_URI as dirname('/do/') gives '/' (or '\') in Windows, when you want '/do/' to be returned.
if (empty($_SERVER['HTTPS']) || $_SERVER['HTTPS'] === 'off') {
$protocol = 'http://';
} else {
$protocol = 'https://';
}
$base_url = $protocol . $_SERVER['SERVER_NAME'] . dirname($_SERVER['PHP_SELF']);
If you want to include the server name, as I understood, then the following code snippets should do what you are asking for:
$result = $_SERVER['SERVER_NAME'] . dirname(__FILE__);
$result = $_SERVER['SERVER_NAME'] . __DIR__; // PHP 5.3
$result = $_SERVER['SERVER_NAME'] . '/' . dirname($_SERVER['REQUEST_URI']);
dirname will give you the directory portion of a file path. For example:
echo dirname('/path/to/file.txt'); // Outputs "/path/to"
Getting the URL of the current script is a little trickier, but $_SERVER['REQUEST_URI'] will return you the portion after the domain name (i.e. it would give you "/do/index.php").
the best way is to use the explode/implode function (built-in PHP) like so
$actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$parts = explode('/',$actual_link);
$parts[count($parts) - 1] = "";
$actual_link = implode('/',$parts);
echo $actual_link;
My Suggestion:
const DELIMITER_URL = '/';
$urlTop = explode(DELIMITER_URL, trim(input_filter(INPUT_SERVER,'REQUEST_URI'), DELIMITER_URL))[0]
Test:
const DELIMITER_URL = '/';
$testURL = "/top-dir";
var_dump(explode(DELIMITER_URL, trim($testURL, DELIMITER_URL))[0]);
$testURL = "/top-dir/";
var_dump(explode(DELIMITER_URL, trim($testURL, DELIMITER_URL))[0]);
$testURL = "/top-dir/test";
var_dump(explode(DELIMITER_URL, trim($testURL, DELIMITER_URL))[0]);
$testURL = "/top-dir/test/";
var_dump(explode(DELIMITER_URL, trim($testURL, DELIMITER_URL))[0]);
$testURL = "/top-dir/test/this.html";
var_dump(explode(DELIMITER_URL, trim($testURL, DELIMITER_URL))[0]);
$testURL = "/top-dir/test.html";
var_dump(explode(DELIMITER_URL, trim($testURL, DELIMITER_URL))[0]);
Test Output:
string(7) "top-dir"
string(7) "top-dir"
string(7) "top-dir"
string(7) "top-dir"
string(7) "top-dir"
string(7) "top-dir"
A shorter (and correct) solution that keeps trailing slash:
$url = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$url_dir = preg_replace('/[^\/]+\.php(\?.*)?$/i', '', $url);
echo $url_dir;
My Contribution
Tested and worked
/**
* Get Directory URL
*/
function get_directory_url($file = null) {
$protocolizedURL = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$trailingslashURL= preg_replace('/[^\/]+\.php(\?.*)?$/i', '', $protocolizedURL);
return $trailingslashURL.str_replace($_SERVER['DOCUMENT_ROOT'], '', $file);
}
USAGE
Example 1:
<?php echo get_directory_ur('images/monkey.png'); ?>This will return http://localhost/go/images/monkey.png
Example 2:
<?php echo get_directory_ur(); ?>This will return http://localhost/go/