How to strip text from string if contained - php

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

Related

PHP Remove middle section of a string

I have a url that will always look like some variation of this
https://sitename/wp-content/uploads/2017/09/59a778097ae6e-150x150.jpeg
I need to remove with PHP the resolution specifier "-150x150" so that it reads
https://sitename/wp-content/uploads/2017/09/59a778097ae6e.jpeg
If it's always -150x150 you can just use str_replace():
$url = "https://sitename/wp-content/uploads/2017/09/59a778097ae6e-150x150.jpeg";
$stripped = str_replace('-150x150', '', $url);
var_dump($stripped);
// string(62) "https://sitename/wp-content/uploads/2017/09/59a778097ae6e.jpeg"
If you need a way to strip out any resolution, you can use a regular expression for that:
$url = "https://sitename/wp-content/uploads/2017/09/59a778097ae6e-150x150.jpeg";
$stripped = preg_replace('/-[0-9]+x[0-9]+/', '', $url);
var_dump($stripped);
// string(62) "https://sitename/wp-content/uploads/2017/09/59a778097ae6e.jpeg"
hello you can use strpos() and substr() functions
<?php
$str1 = "https://sitename/wp-content/uploads/2017/09/59a778097ae6e-150x150.jpeg";
$str2 = "-150x150";
$pos = strpos($str1, $str2);
$part1 = substr($str1, $pos);
$part2 = substr($pos+1, strlen($str1));
$final_str = $part1.$part2;
echo $final_str;
?>
or you can also just use str_replace() and replace the part of the url by nothing :
<?php
$url = "https://sitename/wp-content/uploads/2017/09/59a778097ae6e-150x150.jpeg";
$str = "-150x150";
// will replace $str by '' in $url
$url = str_replace($str, '', $url);
echo $url;
?>
If it's not always 150x150, here's a nifty solution.
$url = 'https://sitename/wp-content/uploads/2017/09/59a778097ae6e-150x150.jpeg';
First get the extension
$ext = explode('.', $url);
$ext = $ext[count($ext)-1];
Then split by '-'
$array = explode('-', $url);
Pop the last array element which will be the resolution (150x150 here)
array_pop($array);
Then implode by '-' again and concatenate the extension to the new url
$new_url = implode('-', $array). '.' .$ext;

Get number from an url in PHP

I have the following url : http:example.com/country/France/45.
With the pattern http:example.com/country/name/**NUMBER**(?$_GET possibly).
How can I extract the number with a regex (or something else then regex) ?
With regexp:
$str = 'http:example.com/country/France/45';
preg_match('/http:example\.com\/country\/(?P<name>\w+)\/(?P<id>\d+)/', $str, $matches);
print_r($matches); // return array("name"=>"France", "id" => 45);
$url = 'http:example.com/country/France/45';
$id = end(explode('/',trim($url,'/')));
Simple isn't ?
The usage of trim () is to remove trailing \
echo $last = substr(strrchr($url, "/"), 1 );
strrchr() will give last occurence of the / character and then substr() gives string after it.
use something like this
$url = "http://example.com/country/France/45";
$parts = explode('/', $url);
$number = $parts[count($parts) - 1];
and if you have GET variable at the end, you can explode further like this
$number = explode('?', $number);
$number = $number[0];
hope this helps :)
the get command for php is $_GET so to show to number do
<html>
<body>
<?php
echo $_GET["eg"];
?>
</body>
</html>
with a URL of http:example.com/country/name/?eg=**NUMBER**
Use explode():
$parts = explode('/', $url);
$number = $parts[count($parts)-1];

How to remove last element in php [duplicate]

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);
}

Using an expression to remove part of a string

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.

How can I url replacing in php

Can someone help me with replacing this url
http://www.izlesene.com/video/arabic-shkira-belly-dance/200012
to: 200012
$url = 'http://www.izlesene.com/video/arabic-shkira-belly-dance/200012';
$out = preg_replace("/[^0-9]/i","",$url);
or
preg_match("/\/([0-9]+)/i",$url,$m);
$out = $m[1];
use the basename
$video_id = basename($url);
var_dump($video_id);
or
try to explode and get the last item.
$url = "http://www.izlesene.com/video/arabic-shkira-belly-dance/200012";
$segments = explode("/",$url);
$video_id = end($segments);
var_dump($video_id);
If things works like in JS you can do it like so:
$url = "http://www.izlesene.com/video/arabic-shkira-belly-dance/200012";
$a = explode("/", $url);
$number = array_pop($a);
And maybe like this:
$url = "http://www.izlesene.com/video/arabic-shkira-belly-dance/200012";
$number = array_pop( explode("/", $url) );
Or you can do it faster without arrays and regex:
$url = "http://www.izlesene.com/video/arabic-shkira-belly-dance/200012";
$url = substr($url, strrpos($url, "/") + 1);
strrpos searches the position of the last occurrence of / in a string and substr returns the portion of a string specified by this position.
Try:
$number = basename($url);
Hint: Regular expressions are not always the best solution (even if quite powerful but also complicated). See basenameDocs.
If you really need a regex, start at the end:
$url = "http://www.izlesene.com/video/arabic-shkira-belly-dance/200012";
$number = preg_replace('~.*/([^/]+)$~', '$1', $url);
^

Categories