I have some php which prints a url. Can I contain this with PHP to leave off the last segment?
So this:
www.mysite.com/name/james
would become this:
www.mysite.com/name
I'm using expression engine so the code is just {site_url}.
$url = (substr($url, -1) == '/') ? substr($url, 0, -1) : $url; // remove trailing slash if present
$urlparts = explode('/', $url); // explode on slash
array_pop($urlparts); // remove last part
$url = implode($urlparts, '/'); // put it back together
Related
I'm wanting to strip out everything from a URL but the domain. So http://i.imgur.com/rA81kQf.jpg becomes imgur.com.
$url = 'http://i.imgur.com/rA81kQf.jpg';
$parsedurl = parse_url($url);
$parsedurl = preg_replace('#^www\.(.+\.)#i', '$1', $parsedurl['host']);
// now if a dot exists, grab everything after it. This removes any potential subdomain
$parsedurl = preg_replace("/^(.*?)\.(.*)$/","$2",$parsedurl);
The above works but I feel like I should only being one preg_replace for this. Any idea how I may combine the two?
You can use parse_url() to get desired output like this,
$url = "http://i.imgur.com/rA81kQf.jpg";
$parseData = parse_url($url);
$domain = preg_replace('/^www\./', '', $parseData['host']);
$array = explode(".", $domain);
echo (array_key_exists(count($array) - 2, $array) ? $array[count($array) - 2] : "") . "." . $array[count($array) - 1];
which prints
imgur.com
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;
I've got a text file containing a lot of URLs. Some of the URLs start with www. and http:// and some them start with nothing.
I want to add www. in front of every line in the text file where the URL does not start with www. or http://.
$lines = file("sites.txt");
foreach($lines as $line) {
if(substr($line, 0, 3) != "www" && substr($line, 0, 7) != "http://" ) {
}
}
That's the code I have right now. I know it's not much, but I have no clue how to add www. in front of every unmatched line.
This will add the www. if not present and it will work if there is http/httpS in the found line.
$url = preg_replace("#http(s)?://(?:www\.)?#","http\\1://www.", $url);
This regex will work on the following:
domain.ext -> http://www.domain.ext
www.domain.ext -> http://www.domain.ext
http://www.domain.ext -> http://www.domain.ext
https://domain.ext -> https://www.domain.ext (note the httpS)
https://www.domain.ext -> https://www.domain.ext (note the httpS)
Regex explained:
http(s)?:// -> The http's S might not be there, save in case it is.
(?:www\.)? -> the www. might not be there. Don't save (?:), we're gonna add it anyways
Then we use the \\1 in the replace value to allow the http**S** to stay working when present.
Also, all the string substr functions will fail on https, because it's 1 character longer.
The trick is to pass $lines by reference so you will be able to alter them:
foreach($lines as &$line) { // note the '&'
// http:// and www. is missing:
if(stripos($line, 'http://www.') === false) {
$line = 'http://www.' . $line;
// only http:// is missing:
} elseif(stripos($line, 'http://www.') !== false && stripos($line, 'http://') === false) {
$line = 'http://' . $line;
// only www. is missing:
} elseif(stripos($line, 'http://') !== 0 && stripos($line, 'www.') !== 0)
$line = 'http://www.' . str_replace('http://', '', $line);
// nothing is missing:
} else {
}
}
Note:
Simply adding www. to a non-www domain can be wrong because www.example.com and example.com CAN have completely different contents, different servers, different destination, different DNS mapping. It's good to add http:// but not to add www..
To write the new array back to the file, you'd use:
file_put_contents(implode(PHP_EOL, $lines), 'sites.txt');
$lines = file("/var/www/vhosts/mon.totalinternetgroup.nl/public/sites/sites.txt");
$new_lines = array();
foreach($lines as $line) {
if(substr($line, 0, 3) != "www" || substr($line, 0, 7) != "http://" ) {
$new_lines[] = "www.".$line;
}else{
$new_lines[] = $line;
}
}
$content = implode("\n", $new_lines);
file_put_contents("/var/www/vhosts/mon.totalinternetgroup.nl/public/sites/sites.txt", $content);
use this:
with only 3 line!
<?
$g0 = file_get_contents("site");
#--------------------------------------------------
$g1 = preg_replace("#^http://#m","",$g0);
$g2 = preg_replace("/^www\./m","",$g1);
$g3 = preg_replace("/^/m","http://",$g2);
#--------------------------------------------------
file_put_contents("site2",$g3);
?>
input file
1.com
www.d.som
http://ss.com
http://www.ss.com
output file:
http://1.com
http://d.som
http://ss.com
http://ss.com
I was trying to get what page the visitor visit:
Here is my code:
$url = $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
$urlcomplete = $url;
$url = explode(".com/",$url);
$urlcount = count($url);
$newurl = '';
for ($start = 1; $start < $urlcount; $start++) {
if ($newurl != '') {
$newurl .= '.com/';
}
$newurl .= $url[$start];
}
$url = explode('/',$newurl);
$urlcount = explode('?',end($url));
$url[count($url) - 1] = $urlcount[0];
$urlcount = count($url);
By using the code above, all the subpage will be store in the $url.
https://stackoverflow.com/questions/ask
$url[0] = 'questions'
$url[1] = 'ask'
Just want to ask, is this good way, or there are others better way?
First prepending SERVER_NAME to the REQUEST_URI, and then trying to split it off, is pointless. This should be a simpler solution:
# first, split off the query string, if any:
list( $path ) = explode( '?', $_SERVER['REQUEST_URI'], 2 );
# then just split the URL path into its components:
$url = explode( '/', ltrim( $path, '/' ) );
The ltrim removes any leading slashes from the path, so that $url[0] won't be empty.
Note that there might still be an empty element at the end of the $url array, if the path ends in a slash. You could get rid of it by using trim instead of ltrim, but you may not want to, since the trailing slash is significant for things like resolving relative URLs.
I need to get the very last word from an URL. So for example I have the following URL:
http://www.mydomainname.com/m/groups/view/test
I need to get with PHP only "test", nothing else. I tried to use something like this:
$words = explode(' ', $_SERVER['REQUEST_URI']);
$showword = trim($words[count($words) - 1], '/');
echo $showword;
It does not work for me. Can you help me please?
Thank you so much!!
Use basename with parse_url:
echo basename(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));
by using regex:
preg_match("/[^\/]+$/", "http://www.mydomainname.com/m/groups/view/test", $matches);
$last_word = $matches[0]; // test
I used this:
$lastWord = substr($url, strrpos($url, '/') + 1);
Thnx to: https://stackoverflow.com/a/1361752/4189000
You can use explode but you need to use / as delimiter:
$segments = explode('/', $_SERVER['REQUEST_URI']);
Note that $_SERVER['REQUEST_URI'] can contain the query string if the current URI has one. In that case you should use parse_url before to only get the path:
$_SERVER['REQUEST_URI_PATH'] = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
And to take trailing slashes into account, you can use rtrim to remove them before splitting it into its segments using explode. So:
$_SERVER['REQUEST_URI_PATH'] = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$segments = explode('/', rtrim($_SERVER['REQUEST_URI_PATH'], '/'));
To do that you can use explode on your REQUEST_URI.I've made some simple function:
function getLast()
{
$requestUri = $_SERVER['REQUEST_URI'];
# Remove query string
$requestUri = trim(strstr($requestUri, '?', true), '/');
# Note that delimeter is '/'
$arr = explode('/', $requestUri);
$count = count($arr);
return $arr[$count - 1];
}
echo getLast();
If you don't mind a query string being included when present, then just use basename. You don't need to use parse_url as well.
$url = 'http://www.mydomainname.com/m/groups/view/test';
$showword = basename($url);
echo htmlspecialchars($showword);
When the $url variable is generated from user input or from $_SERVER['REQUEST_URI']; before using echo use htmlspecialchars or htmlentities, otherwise users could add html tags or run JavaScript on the webpage.
use preg*
if ( preg_match( "~/(.*?)$~msi", $_SERVER[ "REQUEST_URI" ], $vv ))
echo $vv[1];
else
echo "Nothing here";
this was just idea of code. It can be rewriten in function.
PS. Generally i use mod_rewrite to handle this... ans process in php the $_GET variables.
And this is good practice, IMHO
ex: $url = 'http://www.youtube.com/embed/ADU0QnQ4eDs';
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$url_path = parse_url($url, PHP_URL_PATH);
$basename = pathinfo($url_path, PATHINFO_BASENAME);
// **output**: $basename is "ADU0QnQ4eDs"
complete solution you will get in the below link. i just found to Get last word from URL after a slash in PHP.
Get last parameter of url in php