My page URL could be one of the belows:
/lang/part1/part2/
/part1/part2/
I also have a boolean $hasLocale that is TRUE if lang is in the URL, otherwise it's FALSE if it's not.
I need to add a string before part1, so my URL could become:
/lang/somestring/part1/part2/
/somestring/part1/part2/
This is my code:
if ($hasLocale) {
$urlArray = explode('/', $url);
array_splice( $urlArray, 1, 0, ['somestring'] );
$newUrl = '/' . implode('/', $urlArray);
}
else {
$newUrl = '/somestring' . $url;
}
Is there a better way to do this?
Use a regexp replacement.
if ($hasLocale) {
$newUrl = preg_replace('#^/[^/]*#', '$0/somestring', $url);
} else {
$newUrl = '/somestring' . $url;
}
The regexp matches the initial / followed by everything up to, but not including, the next /. $0 in the replacement is replaced with whatever that matched.
DEMO
Here's a fun way. Get before part1 concatenate with somestring and concatenate with what's after part1:
$newUrl = strstr($url, 'part1', true) . 'somestring/' . strstr($url, 'part1');
Related
I have a string $current_url that can contain 2 different values:
http://url.com/index.php&lang=en
or
http://url.com/index.php&lang=jp
in both cases I need to strip the query part so I get: http://url.com/index.php
How can I do this in php?
Thank you.
Simplest Solution
$url = 'http://url.com/index.php&lang=en';
$array = explode('&', $url);
echo $new_url =$array[0];
To only remove the lang query do this
$url = 'http://url.com/index.php&lang=en&id=1';
$array = explode('&lang=en', $url);
echo $new_url = $array[0] .''.$array[1];
//output http://url.com/index.php&id=1
So this way it only removes the lang query and keep other queries
If the value of your lang parameter is always of length 2, which should be the case for languages, you could use:
if(strpos($current_url, '&lang=') !== false){
$current_url = str_replace(substr($current_url, strpos($current_url, '&lang='), 8), '', $current_url);
}
If the substring "&lang=" is present in $current_url, it removes a substring of length 8, starting at the "&lang=" position. So it basically removes "&lang=" plus the 2 following chars.
You can Use strtok to remove the query string from url.
<?php
echo $url=strtok('http://url.com/index.php&lang=jp','&');
?>
DEMO
Answer based on comment.
You can use preg_replace
https://www.codexworld.com/how-to/remove-specific-parameter-from-url-query-string-php/
<?php
$url = 'http://url.com/index.php?page=site&lang=jp';
function remove_query_string($url_name, $key) {
$url = preg_replace('/(?:&|(\?))' . $key . '=[^&]*(?(1)&|)?/i', "$1", $url_name);
$url = rtrim($url, '?');
$url = rtrim($url, '&');
return $url;
}
echo remove_query_string($url, 'lang');
?>
DEMO
This question already has answers here:
Strip off specific parameter from URL's querystring
(22 answers)
Closed 8 years ago.
I have to remove the last element in a string. I used rtrim in php but it is not working.
This is the string:
/search/listing.html?vehicle_type=&year=&make_name=&model_name=&loc_type=3&zipcode=641004&distance=100&make_order=ASC
I need to remove "&make_order=ASC"
Can anyone help me?
$s = '/search/listing.html?vehicle_type=&year=&make_name=&model_name=&loc_type=3&zipcode=641004&distance=100&make_order=ASC';
echo substr($s, 0, strrpos($s, '&'));
Edit:
$url = $base_url.trim( $_SERVER['REQUEST_URI'], "&year_order=".$arr['year_order']."" );
// ^
// |_ replace , with .
trim should work:
$string = "/search/listing.html?vehicle_type=&year=&make_name=&model_name=&loc_type=3&zipcode=641004&distance=100&make_order=ASC";
$string = trim($string, "&make_order=ASC");
There's no guarantee that make_order will be at the end of the query string - or exist at all. To remove the field properly, you'd have to use something like this:
$url = '/search/listing.html?vehicle_type=&year=&make_name=&model_name=&loc_type=3&zipcode=641004&distance=100&make_order=ASC';
// break down the URL into a path and query string
$parsed = parse_url($url);
// turn the query string into an array that we can manipulate
$qs = array();
parse_str($parsed['query'], $qs);
// remove the unwanted field
unset($qs['make_order']);
// rebuild the URL
$rebuilt = $parsed['path'];
if(!empty($qs)) {
$rebuilt .= '?' . http_build_query($qs);
}
echo $rebuilt;
$actual_link = "/search/listing.html?vehicle_type=&year=&make_name=&model_name=&loc_type=3&zipcode=641004&distance=100&make_order=ASC";
echo str_replace("&make_order=ASC","",$actual_link);
$string = "/search/listing.html?vehicle_type=&year=&make_name=&model_name=&loc_type=3&zipcode=641004&distance=100&make_order=ASC";
$args = array_pop(explode($string, "&"));
$string = implode("&", $args);
There are a bunch of ways. The easiest might be:
$i=strrpos($text,'&');
$newstring=substr($text,0,$i);
$str = "/search/listing.html?vehicle_type=&year=&make_name=&model_name=&loc_type=3&zipcode=641004&distance=100&make_order=ASC";
echo $str . "<br>";
echo trim($str,"&make_order=ASC");
if &make_order=ASC is always going to be at the end, you can use strstr() to do this
$str = '/search/listing.html?vehicle_type=&year=&make_name=&model_name=&loc_type=3&zipcode=641004&distance=100&make_order=ASC';
echo strstr($str,'&make_order=ASC',true);
Remove desired key from url.
Use:
$s = '/search/listing.html?vehicle_type=&year=&make_name=&model_name=&loc_type=3&zipcode=641004&distance=100&make_order=ASC';
echo remove_key_from_url($url, 'make_order');
Output :
/search/listing.html?vehicle_type=&year=&make_name=&model_name=&loc_type=3&zipcode=641004&distance=100
Code:
function remove_key_from_url($url, $key) {
if (strpos($url, '?') === false) return $url;
list($left, $right) = explode('?', $url, 2);
parse_str($right, $get);
if (isset($get[$key])) unset($get[$key]);
return $left . '?' . http_build_query($get);
}
This is probably simple however I am not the best with expressions..
I am trying to get the following string from..
http://www.yoursite.com/offers/838?&SITEID=2172
to this.. using an expression that will remove the ?&SITEID and the dynamic id which will vary
http://www.yoursite.com/offers/838
Can anyone suggest the best/simplest method to do this?
Check this function:
$str = 'http://www.yoursite.com/offers/838?&SITEID=2172';
function remove_query_arg($var, $url = NULL){
if(!$url){
$url = $_SERVER['REQUEST_URI'];
}
$parsed_url = parse_url($url);
$query_vars = explode('&', $parsed_url['query']);
foreach($query_vars as $key => $value){
$query_vars[$key] = explode('=', $query_vars[$key]);
$query_variables[$query_vars[$key][0]] = $query_vars[$key][1];
}
if(is_array($var)){
foreach($var as $value){
unset($query_variables[$value]);
}
}
elseif(is_string($var)){
unset($query_variables[$var]);
}
$query_vars = array();
foreach($query_variables as $key => $value){
$query_vars[] = $key.($value !== NULL || !empty($value) ? '='.$value : '');
}
$query_str = '';
$query_str = implode('&',$query_vars);
return (isset($parsed_url['scheme']) && !empty($parsed_url['scheme']) ? $parsed_url['scheme'].'://' : '').$parsed_url['host'].(isset($parsed_url['path']) && !empty($parsed_url['path']) ? $parsed_url['path'] : '').(!empty($query_str) ? '?'.$query_str : '');
}
echo remove_query_arg('SITEID', $str);
This is a URL, so parse it as one, with parse_url().
$url = "http://www.yoursite.com/offers/838?&SITEID=2172";
$parts = parse_url($url);
$url = $parts["scheme"] . "://" . $parts["host"] . $parts["path"];
Using explode function returns an array
$url=http://www.yoursite.com/offers/838?&SITEID=2172
$result=explode('?',$url)
print_r($result);
output
array
{
[0]=>http://www.yoursite.com/offers/838
[1]=>?&SITEID=2172
}
A valid URL only has one ? so you can just use explode to break it into 2 parts
$url = "http://www.yoursite.com/offers/838?&SITEID=2172";
list($path, $query) = explode("?", $url, "2");
var_dump($path);
Output
string 'http://www.yoursite.com/offers/838' (length=34)
$url = "http://www.yoursite.com/offers/838?&SITEID=2172";
$str = substr($url, strpos($url, 0, "?&SITEID"));
// $str results in "http://www.yoursite.com/offers/838"
If you want to keep the part before the ? you can search
^(.+?)(\?&SITEID|$)
and replace with
$1
You search non greedily from the beginning of the line ^ to the first ?&SITEID and leave out the rest. If no ?&SITEID is found you get the entire line by arriving at the end of the string with $
| is the OR operator that tells the regex "Stop at the first ?&SITEID or at the end of the string"
EDIT:
After the comment where you explain your need to keep the rest of the querystring I suggest you a different approach: find
&?SITEID=[^&\s]+
being
&? an optional & at the beginning of the string
SITEID= the string you are looking for followed by
[^&\s]+ any number of non&, nonspace character
and remove it from the string. However, being this the case, I'd go with a non-regex, url-specific approach like suggested in the other answers.
First, I need to check the URL string, if the protocol of URL is https, then I need to replace http in PHP.
So the inputs and outputs of this php function must be like this:
Input -> https://example.com/example/https.php
Output-> http://example.com/example/https.php
Input -> http://example.com/example/https.php
Output-> http://example.com/example/https.php
This will ensure it's at the beginning of the string and it's followed by ://
$input = 'https://example.com/example/https.php';
echo preg_replace('/^https(?=:\/\/)/i','http',$input);
function remove_ssl ($url) {
if (strpos($url, 'https://') == 0) {
$url = 'http://' . substr($url, 7);
}
return $url;
}
The
strpos($url, 'https://') == 0
Is on purpose and is not === because we only want the case when the URL starts with https:// and just replace that one.
See also: http://php.net/manual/en/function.parse-url.php
...
$parsed_url = parse_url($url);
if ($parsed_url['scheme'] == 'https') {
$url = 'http://' . substr($url, 7);
}
return $url;
...
At first you need to check https presence with strpos():
if( strpos( $url, 'https://') === 0){
(notice ===), than you may extract the all string after https:// (that's after first 8 characters, or 5 when keeping original ://) with substr():
$url = 'http://' . substr( $url, 8);
$parse = parse_url($url);
if($parse['scheme'] === 'https')
{
$url = str_replace('https','http',$url,1);
}
You can use this solution.
You can use a combination of str_pos() and str_replace() to accomplish this:
if(str_pos($input,'https:') === 0) {
$output = str_replace('https:','http:',$input,1);
} else {
$output = $input;
}
function replace_uri_protocol($uri, $search, $replacement){
$parts = parse_url($uri);
$uri = $replacement."://".$parts["host"].$parts["path"];
if(isset($parts["query"])){
$uri .= "?".$parts["query"];
}
return $uri;
}
Try this it's work on me..
$url = 'https://www.example.com';
echo preg_replace("(^https?://)", "http://", $url);
I need a php function which produce a pure domain name from URL. So this function must be remove http://, www and /(slash) parts from URL if these parts exists. Here is example input and outputs:
Input - > http://www.google.com/ | Output -> google.com
Input - > http://google.com/ | Output -> google.com
Input - > www.google.com/ | Output -> google.com
Input - > google.com/ | Output -> google.com
Input - > google.com | Output -> google.com
I checked parse_url function, but doesn't return what I need.
Since, I'm beginner in PHP, it was difficult for me. If you have any idea, please answer.
Thanx in advance.
$input = 'www.google.co.uk/';
// in case scheme relative URI is passed, e.g., //www.google.com/
$input = trim($input, '/');
// If scheme not included, prepend it
if (!preg_match('#^http(s)?://#', $input)) {
$input = 'http://' . $input;
}
$urlParts = parse_url($input);
// remove www
$domain = preg_replace('/^www\./', '', $urlParts['host']);
echo $domain;
// output: google.co.uk
Works correctly with all your example inputs.
$str = 'http://www.google.com/';
$str = preg_replace('#^https?://#', '', rtrim($str,'/'));
echo $str; // www.google.com
There are lots of ways grab the domain out of a url I've posted 4 ways below starting from the shortest to the longest.
#1
function urlToDomain($url) {
return implode(array_slice(explode('/', preg_replace('/https?:\/\/(www\.)?/', '', $url)), 0, 1));
}
echo urlToDomain('http://www.example.com/directory/index.php?query=true');
#2
function urlToDomain($url) {
$domain = explode('/', preg_replace('/https?:\/\/(www\.)?/', '', $url));
return $domain['0'];
}
echo urlToDomain('http://www.example.com/directory/index.php?query=true');
#3
function urlToDomain($url) {
$domain = preg_replace('/https?:\/\/(www\.)?/', '', $url);
if ( strpos($domain, '/') !== false ) {
$explode = explode('/', $domain);
$domain = $explode['0'];
}
return $domain;
}
echo urlToDomain('http://www.example.com/directory/index.php?query=true');
#4
function urlToDomain($url) {
if ( substr($url, 0, 8) == 'https://' ) {
$url = substr($url, 8);
}
if ( substr($url, 0, 7) == 'http://' ) {
$url = substr($url, 7);
}
if ( substr($url, 0, 4) == 'www.' ) {
$url = substr($url, 4);
}
if ( strpos($url, '/') !== false ) {
$explode = explode('/', $url);
$url = $explode['0'];
}
return $url;
}
echo urlToDomain('http://www.example.com/directory/index.php?query=true');
All of the functions above return the same response: example.com
Try this, it will remove what you wanted (http:://, www and trailing slash) but will retain other subdomains such as example.google.com
$host = parse_url('http://www.google.com', PHP_URL_HOST);
$host = preg_replace('/^(www\.)/i', '', $host);
Or as a one-liner:
$host = preg_replace('/^(www\.)/i', '', parse_url('http://www.google.com', PHP_URL_HOST));
if (!preg_match('/^http(s)?:\/\//', $url))
$url = 'http://' . $url;
$host = parse_url($url, PHP_URL_HOST);
$host = explode('.', strrev($host));
$host = strrev($host[1]) . '.' strrev($host[0]);
This would return second level domain, though it would be useless for say .co.uk domains, so you might want to do some more checking, and include additional parts if strrev($host[0]) is uk, au, etc.
$value = 'https://google.ca';
$result = str_ireplace('www.', '', parse_url($value, PHP_URL_HOST));
// google.ca
First way is to use one regular expression to trim unnecesary parts of URL like protocol, www and ending slash
function trimUrlProtocol($url) {
return preg_replace('/((^https?:\/\/)?(www\.)?)|(\/$)/', '', trim($url));
}
echo trimUrlProtocol('http://sandbox.onlinephpfunctions.com/') . PHP_EOL;
echo trimUrlProtocol('https://sandbox.onlinephpfunctions.com/') . PHP_EOL;
echo trimUrlProtocol('http://www.sandbox.onlinephpfunctions.com/') . PHP_EOL;
echo trimUrlProtocol('https://www.sandbox.onlinephpfunctions.com/') . PHP_EOL;
echo trimUrlProtocol('http://sandbox.onlinephpfunctions.com') . PHP_EOL;
echo trimUrlProtocol('https://sandbox.onlinephpfunctions.com') . PHP_EOL;
echo trimUrlProtocol('http://www.sandbox.onlinephpfunctions.com') . PHP_EOL;
echo trimUrlProtocol('https://www.sandbox.onlinephpfunctions.com') . PHP_EOL;
echo trimUrlProtocol('sandbox.onlinephpfunctions.com') . PHP_EOL;
By alternative way you can use parse_url, but you have to make additional cheks to check if host part exists and then use regular expression to trim www. Just use first way, it is simple and lazy.
This will account for "http/https", "www" and the ending slash
$str = 'https://www.google.com/';
$str = preg_replace('#(^https?:\/\/(w{3}\.)?)|(\/$)#', '', $str);
echo $str; // google.com
Just ask if you need help understanding the regex.
Use parse_url
http://www.php.net/manual/en/function.parse-url.php