How to get first 3 parts of URL in PHP? - php

How to get first 3 parts of current URL by using PHP.
For example:
My Url: http://something.com/somebody/somegirls/whatever/
The result after getting parts: http://something.com/somebody/somegirls/
This is my code PHP which get current URL:
<?php function curPageURL() {
$url = isset( $_SERVER['HTTPS'] ) && 'on' === $_SERVER['HTTPS'] ? 'https' : 'http';
$url .= '://' . $_SERVER['SERVER_NAME'];
$url .= in_array( $_SERVER['SERVER_PORT'], array('80', '443') ) ? '' : ':' . $_SERVER['SERVER_PORT'];
$url .= $_SERVER['REQUEST_URI'];
return $url;
}
$current_url = str_replace("www.", "", curPageURL());
?>

Try this,
<?php
$url = 'http://something.com/somebody/somegirls/whatever/';
$parts = explode('/', $url);
$new_url = $parts[0].'/'.$parts[1].'/'.$parts[2].'/'.$parts[3].'/'.$parts[4].'/';
echo $new_url;
?>
OUTPUT
http://something.com/somebody/somegirls/

Assuming that you have grabbed this URL from your function...
<?php
$url='http://www.something.com/somebody/somegirls/whatever/';
$parts=explode('/',parse_url($url)['path']);
array_unshift($parts,trim(strstr(parse_url($url)['host'],'.'),'.'));
print_r(array_filter($parts));
OUTPUT :
Array
(
[0] => something.com
[2] => somebody
[3] => somegirls
[4] => whatever
)
Demonstration

You can also use parse_url to get the url in parts in an array like this:
$current_url_array = parse_url($current_url);
var_dump($current_url_array);

You can use regexp:
<?php
function getFirstUrlContents($Url) {
preg_match_all('/^([^\/]*\/){5}/', $Url, $MatchesArray);
return $MatchesArray[0];
}
var_dump(getFirstUrlContents('http://something.com/somebody/somegirls/whatever/'));
?>

<?php
$url='http://something.com/somebody/somegirls/whatever' ;
$explode=explode("/", $url);
$search=end($explode);
echo $currentUrl=str_replace($search,'',$url);
?>
Output
http://something.com/somebody/somegirls/

Try with this :
<?php
$url = 'http://something.com/somebody/somegirls/whatever/';
$pos = explode('/', $url);
for($i=0; $i<5; $i++){
echo $pos[$i].'/';
}
?>
Output: http://something.com/somebody/somegirls/

Please check the below code.
function createUrl($array, $pos) {
$string = '';
for ($i = 0; $i < $pos; $i++)
$string .=$array[$i].'/';
return $string;
}
$current_url = "http://something.com/somebody/somegirls/xyz/yui";
$initial_string = (stripos($current_url, 'https://') !== FALSE)
? 'https://'
: ((strpos($a, 'http://') !== FALSE)
? 'http://' : '');
$last_string = explode('/', substr($a, strlen($initial_string)));
$final_url = $initial_string.
(count($last_string) > 3)
? createUrl($last_string, 3)
: substr($current_url, strlen($initial_string));
echo $final_url;

Related

How to store numeric value of the first 1-character alphabetical parameter in a URL?

I want to store in a session, a value (a number) of the first 1-character alphabetical string that shows in the URL, as long as it is not a.
Examples, if visitor arrives to:
mydomain.com/nice-url/?a=1&p=2&v=3&vt_p=5
Then the number that should be stored is 2
(something like $_SESSION['number']=2)
mydomain.com/nice-url/?a=2&v=7
Then the number that should be stored is 7
mydomain.com/nice-url/?z=3&
Then the number that should be stored is 3
mydomain.com/nice-url/?a=1&pv=2&s=30&p=5
Then the number that should be stored is 30
mydomain.com/nice-url/?a=1&v=z&m=8
Then the number that should be stored is 8
I'm already using following code for another use, so perhaps a part of this code can be utilized for this goal as well:
function unparse_url($parsed_url) {
$scheme = isset($parsed_url['scheme']) ? $parsed_url['scheme'] . '://' : '';
$host = isset($parsed_url['host']) ? $parsed_url['host'] : '';
$port = isset($parsed_url['port']) ? ':' . $parsed_url['port'] : '';
$user = isset($parsed_url['user']) ? $parsed_url['user'] : '';
$pass = isset($parsed_url['pass']) ? ':' . $parsed_url['pass'] : '';
$pass = ($user || $pass) ? "$pass#" : '';
$path = isset($parsed_url['path']) ? $parsed_url['path'] : '';
$query = !empty($parsed_url['query']) ? '?' . trim($parsed_url['query'], '&') : '';
$fragment = isset($parsed_url['fragment']) ? '#' . $parsed_url['fragment'] : '';
return "$scheme$user$pass$host$port$path$query$fragment";
}
function strip_query($url, $query_to_strip) {
$parsed = parse_url($url);
$parsed['query'] = preg_replace('/(^|&)'.$query_to_strip.'[^&]*/', '', $parsed['query']);
return unparse_url($parsed);
}
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
The solution using parse_url, explode and is_numeric functions:
$url = "mydomain.com/nice-url/?a=1&pv=2&s=30&p=5";
$query_papams = explode("&", parse_url($url, PHP_URL_QUERY));
$number = "not found";
foreach ($query_papams as $p) {
$pair = explode("=", $p);
if (strlen($pair[0]) == 1 && $pair[0] !== "a" && is_numeric($pair[1])) {
$number = $pair[1];
break;
}
}
print_r($number); // 30
You could use a simple function to get around this. Here you go:
<?php
$url1 = "mydomain.com/nice-url/?a=1&p=2&v=3&vt_p=5";
$url2 = "mydomain.com/nice-url/?a=2&v=7";
$url3 = "mydomain.com/nice-url/?a=1&pv=2&s=30&p=5";
$url4 = "mydomain.com/nice-url/?a=1&v=z&m=8";
$url5 = "mydomain.com/nice-url/?z=3&jk=23";
function getSavableNumberFromURL($uri){
$objStripped = new stdClass();
$objParsedQuery = new stdClass();
if(!stristr($uri, "?")){
$objStripped->RQ_URI = $uri;
$objStripped->QUERY = null;
}else{
$arrSplit = preg_split("#\?#", $uri);
$objStripped->RQ_URI = $arrSplit[0];
$objStripped->QUERY = $arrSplit[1];
}
$queryString = $objStripped->QUERY;
$queryString = preg_replace("#(^\?)#", "", $queryString);
$arrSplit = preg_split("#\&#", $queryString);
if(!empty($arrSplit) && count($arrSplit)>1 ) {
foreach ($arrSplit as $queryKVPair) {
preg_match("#(.*)(\=)(.*)#", $queryKVPair, $matches);
list($fullNull, $key, $null, $value) = $matches;
$objParsedQuery->$key = $value;
}
}
foreach($objParsedQuery as $propName=>$propVal){
if($propName != "a" && strlen($propName) == 1 && is_numeric($propVal)){
return $propVal;
}
}
return null;
}
$savableNum1 = getSavableNumberFromURL($url1);
$savableNum2 = getSavableNumberFromURL($url2);
$savableNum3 = getSavableNumberFromURL($url3);
$savableNum4 = getSavableNumberFromURL($url4);
$savableNum5 = getSavableNumberFromURL($url5);
var_dump($savableNum1); //DISPLAYS: "2"
var_dump($savableNum2); //DISPLAYS: "7"
var_dump($savableNum3); //DISPLAYS: "30"
var_dump($savableNum4); //DISPLAYS: "8"
var_dump($savableNum5); //DISPLAYS: "3"
// YOU CAN THEN STORE THE VALUES
// USING YOUR FAVORITE MECHANISM ($_SESSION) PERHAPS...
//
//
Test it HERE.

What is most effective and fastest way to remove string from beginning? (PHP micro-optimisation)

I have a string like www.host.com and I need to remove beginning from it (in this case www.) to make it just host.com. There is array of these beginnings (like: m., wap. and so on). How to do it in effective and fast way?
Currently I am using this code, but I think there should be a better/faster/cleaner way:
<?php
function _without_start( $val, $start )
{
if( _starts( $val, $start ) )
{
$len = mb_strlen( $start );
$val = mb_substr( $val, $len );
}
return $val;
}
function _starts( $str, $needle )
{
return ( mb_substr( $str, 0, mb_strlen($needle) ) === $needle );
}
/********************************************/
$host = 'www.host.com';
$remove_from_beginning = array( 'www.', 'wap.', 'admin.' );
foreach( $remove_from_beginning as $start )
{
$host = _without_start( $host, $start );
}
var_dump( $host );
You dont need foreach for removing somethings from string, this one will be better,
$url = preg_replace("/^(www|wap)\./si","","www.wap.com");
echo $url;
With explode and in_array:
function _without_start($host, $prefixes) {
list($prefix, $remainder) = explode('.', $host, 2);
return in_array($prefix, $prefixes) ? $remainder : $host;
}
$prefixes = ['www', 'wap', 'admin'];
$host = 'www.host.com';
echo _without_start($host, $prefixes);
Since you added a Regex tag you can make a list using alteration in regex and check it against the string and replace with empty string.
Regex: ^(www|admin|wap)\.
Regex101 Demo
If you are up for a regex based solution (as one of the tag mentions regex), here you go
$remove_from_beginning = array( 'www.', 'wap.', 'admin.' );
$final = "";
foreach( $remove_from_beginning as $start )
{
$final = $final . "" . substr_replace($start, '', -1) . "" . "\.|";
}
$final = substr_replace($final, '', -1);
echo preg_replace("/" . "" . "(?:" . "" . $final . "" . ")" . "" . "(.*)" . "" . "/", "$1", "www.exaple.com");
Ideone Demo

How to determine whether the URL is containing argument(s)?

I have two kind of URLs:
First:
localhost/search?q=arg1&s=arg2
Second:
localhost/search/arg1/arg2
Note: Sometimes arguments are containing ?. Like this:
localhost/search/ar?g1/arg2 // this is belong to second kind
Well, How can I detect ths URL is which kind?
Here is my code:
$FirstKind = strpos($_SERVER['REQUEST_URI'], '?') ? true : false;
But the above code returns true for the URL if one of arguments be containing ? (as you see in the Note above).
You can use parse_url for this:
$parsed = parse_url ( 'YourURL' );
The GET ‘arguments’ are now in $parsed['query']
See more about parse_url()
Here's a possible implementation:
<?php
function getArg($arg, $url) {
$result = '';
$urlData = explode('&', parse_url($url)['query']);
foreach ($urlData as $urlPair) {
if (strpos($urlPair, '=') !== false) {
list($k, $v) = explode('=', $urlPair);
if (trim($k) == $arg) {
$result = trim($v);
break;
}
}
}
if (empty($result)) {
$urlParts = explode('/', $url);
for ($i = 0; $i < sizeof($urlParts); $i++) {
if (trim($urlParts[$i]) == trim($arg)) {
if (isset($urlParts[$i+1])) {
$result = $urlParts[$i+1];
break;
}
}
}
}
return $result;
}
Usage:
$url1 = 'localhost/search?q=arg1&s=arg2';
$url2 = 'localhost/search/ar?g1/arg2';
echo "<pre>";
var_dump(getArg('q', $url1));
var_dump(getArg('ar?g1', $url2));
echo "<pre>";
Outputs:
string(4) "arg1"
string(4) "arg2"

PHP: Convert URL to regular expression to match specific domain

I want to convert a URL to regular expression to match it with current URL. For example, I have a URL http://www.example.com/example.php
I want it to convert to
^(https?://)?(www\.)?example\.com\/example\.php/?(\?.)?(#.)?$
So that I store it and whenever a user hits this url with any number of parameters attached to it, I will match that url with my regular expression and will perform some action based on the results.
I have found many questions but they all are either to match general URL (with any domain name) or with regular expressions given. But I want a function to which I will pass URL and it will return its regular expression and I will use it to match that specific domain.
I have finally created this code with the help of stackoverflow and other communities. This provides me the exact string I require against given URL.
<?php
function createrRegex($url) {
$var1 = '^(https?://)?';
$host = parse_url($url, PHP_URL_HOST);
$host_parts = explode('.', $host);
if (!empty($host_parts)) {
$length = count($host_parts);
foreach ($host_parts as $i => $part) {
if ($i == 0) {
if ($part == "www") {
$var1 .= '(' . $part . '\\\\.)?';
} else {
$var1 .= '' . $part;
$var1 .= ($i < ($length - 1)) ? '\\\\.' : '';
}
} else {
$var1 .= '' . $part;
$var1 .= ($i < ($length - 1)) ? '\\\\.' : '';
}
}
}
$path = '';
if ((parse_url($url, PHP_URL_PATH) != NULL)) {
$path = str_replace('/', '\\\\/', parse_url($url, PHP_URL_PATH));
$path = str_replace('.', '\\\\.', $path);
}
$var1 .= $path;
$var1 .= '/?(\\\\?.*)?(#.*)?$';
return $var1;
}
?>

Validate url and convert into protocol format

I am using file_get_content($url) which does not work with url starting from www.
So I am trying to append the http:// and converting into proper form if user entered url is not in correct form.
Check DEMO HERE
<?php
$url= 'www.google.com';
$pad = 'http://';
$cmp = 'www';
$prefix = substr($url , 0,2);
if($cmp == $prefix)
{
echo str_pad($url, strlen($url)+3 ,"$pad",STR_PAD_LEFT);
}
?>
This code does not echo correct url. Any issue here?
Why not use parse_url to figure it out?
$url = "www.example.com/test.php";
$parsedUrl = parse_url($url);
if(!array_key_exists('scheme', $parsedUrl)){
$url = "http://" . $url;
}
echo $url;
codepad example.
This is all you need:
if (strpos($url, '://') === false)
$url = 'http://' . $url;
check this
$url= 'www.google.com';
$pad = 'http://';
$cmp = 'www';
$prefix = substr($url , 0,3);
if($cmp == $prefix)
{
echo str_pad($url, strlen($url)+7 ,"$pad",STR_PAD_LEFT);
}

Categories