Using an expression to remove part of a string - php

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.

Related

How to strip text from string if contained

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

str ireplace PHP parts of url

I have a html doc that has links in it.
Example :
http://mysite1.com/test/whatIwant/Idontwantthis
http://mysite1.com/test/whatIwant2/Istilldontwantthis
http://mysite1.com/test/whatIwant3/Idontwantthiseither
I want to replace these with:
http://myothersite.com/whatIwant
http://myothersite.com/whatIwant2
http://myothersite.com/whatIwant3
How can I do this? I feel like the only way is to use str_ireplace to get the value that I want and append it to the other link, I just can't seem to remove the part after the value that I want.
I use:
$var= str_ireplace("http://mysite1.com/test/", "http://myothersite.com/", $var);
But then I get the after value still on the link:
http://myothersite.com/whatIwant/Idontwantthis
I tried and now am turning to the community for help.
Thanks
Oh and they are enclosed in the tag with class and other attributes, all I need to change is the URL as explained above.
The links are not in an array they are being edited from a javascript file so they will be in a large variable as text.
$examples =
'http://mysite1.com/test/whatIwant/Idontwantthis http://mysite1.com/test/whatIwant2/Istilldontwantthis http://mysite1.com/test/whatIwant2/Istilldontwantthis
http://mysite1.com/test/whatIwant3/Idontwantthiseither'
;
Edit: using your updated example, you can split those URLs up by the whitespace between them:
$examples = 'http://mysite1.com/test/whatIwant/Idontwantthis http://mysite1.com/test/whatIwant2/Istilldontwantthis http://mysite1.com/test/whatIwant2/Istilldontwantthis http://mysite1.com/test/whatIwant3/Idontwantthiseither';
$examples = explode(' ', $examples);
Alternative example array:
$examples = array(
'http://mysite1.com/test/whatIwant/Idontwantthis',
'http://mysite1.com/test/whatIwant2/Istilldontwantthis',
'http://mysite1.com/test/whatIwant3/Idontwantthiseither'
);
Regex solution:
$pattern = '/^(?:http|https):\/\/.+\/.*\/(.+)\/.*$/Um';
$replace = 'http://myothersite.com/$1';
foreach($examples as $example) {
echo preg_replace($pattern, $replace, $example);
}
Non-regex solution:
foreach($examples as $example) {
// remove the original domain name
$first = str_ireplace('http://mysite1.com/test/', '', $example);
// prepend the new domain name with the first part of the remaining URL
// e.g. strip everything after the first slash
echo 'http://myothersite.com/' . explode('/', $first)[0];
}
Note: using explode(...)[0] is array dereferencing, and is supported in PHP >= 5.4.0. For previous versions of PHP, use a variable to store the array before referencing it:
$bits = explode('/', $first);
echo 'http://myothersite.com/' . $bits[0];
From the manual:
As of PHP 5.4 it is possible to array dereference the result of a function or method call directly. Before it was only possible using a temporary variable.
Example output:
http://myothersite.com/whatIwant
http://myothersite.com/whatIwant2
http://myothersite.com/whatIwant3
This function should do the job.
<?php
function EditLink($link)
{
$link = explode("/",$link);
return $link[4];
}
$new_link = "http://myothersite.com/".EditLink("http://mysite1.com/test/whatIwant/Idontwantthis")."";
echo $new_link;
?>
Try this no regex:
$urls = array(
'http://mysite1.com/test/whatIwant3/Idontwantthiseither',
'http://mysite1.com/test/whatIwant/Idontwantthis',
'http://mysite1.com/test/whatIwant2/Istilldontwantthis'
);
$new_site = "http://myothersite.com/";
foreach ($urls as $url) {
$pathinfo = pathinfo($url);
$base = basename($pathinfo['dirname']);
$var = str_ireplace($url, $new_site . $base, $url);
echo $var . '<br>';
}
As of PHP 5.3:
$new_urls = array_map(function($url) { // anonymous function
global $new_site;
$pathinfo = pathinfo($url);
$base = basename($pathinfo['dirname']);
$var = str_ireplace($url, $new_site . $base, $url);
return $var;
}, $urls);
echo implode('<br>', $new_urls);
Sorry by my last answer, you was right, the order was correct.
Try this one with pre_replace, I beleave could solve the problem:
$var = "http://mysite1.com/test/whatIwant/Idontwantthis";
$var = preg_replace("/http\:\/\/mysite1.com\/([^\/]+)\/?.*/", "http://myothersite.com/$1", $var);
echo $var;

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

preg_replace for Get Parameter - /index.php?color=blue&size=xl

I have this url /index.php?color=blue&size=xl
to get rid of the get parameter, I use this code:
$done = preg_replace('/(.*)(\?|&)color=[^&]*(?(1)&|)?/i', "$1", $url);
echo $done;
"output: index.phpsize=xl"
Now I need to clean the "size" part too. Have tried with two lines of preg_replace, but it doesn´t work.
$done = preg_replace('/(.*)(\?|&)color=[^&]*(?(1)&|)?/i', "$1", $url);
echo $done;
$done2 = preg_replace('/(.*)(\?|&)size=[^&]*(?(1)&|)?/i', "$1", $done);
Edit: I really need a solution where I can clean the exact parameter "color" or "size".
Sometimes I will only delete one of them.
Edit2:
Have this solution:
// Url is: index.php?color=black&size=xl&price=20
function removeqsvar($url, $varname) {
return preg_replace('/([?&])'.$varname.'=[^&]+(&|$)/','$1',$url);
}
$url = removeqsvar($url, color);
echo removeqsvar($url, price);
// will output: index.php?size=xl
Thank you all.
This will allow you to exactly specify which parameters to remove using the $remove array. It works by parsing the URL with parse_url(), then grabbing the query string and parsing it with parse_str().
From there, it's straightforward - Iterate over the parameters in the URL, if one of them is in the $remove array, then delete it from the $params array. By the end, if we have parameters to add to the URL, we add them back with http_build_query().
$url = '/index.php?color=blue&size=xl'; // Your input URL
$remove = array( 'color', 'size'); // Change this to remove what you want
$parts = parse_url( $url);
parse_str( $parts['query'], $params);
foreach( $params as $k => $v) {
if( in_array( $k, $remove)) {
unset( $params[$k]);
}
}
$url = $parts['path'] . ((count( $params) > 0) ? '?' . http_build_query( $params) : '');
echo $url;
list($done) = explode("?", $url);
This snytax also works in PHP 5.3 and lower
try this:
$result = explode('?', $url)[0];
for a php version lower than php 5.4:
$tmp = explode('?', $url);
$result = $tmp[0];

remove a part of a URL argument string in php

I have a string in PHP that is a URI with all arguments:
$string = http://domain.com/php/doc.php?arg1=0&arg2=1&arg3=0
I want to completely remove an argument and return the remain string. For example I want to remove arg3 and end up with:
$string = http://domain.com/php/doc.php?arg1=0&arg2=1
I will always want to remove the same argument (arg3), and it may or not be the last argument.
Thoughts?
EDIT: there might be a bunch of wierd characters in arg3 so my prefered way to do this (in essence) would be:
$newstring = remove $_GET["arg3"] from $string;
There's no real reason to use regexes here, you can use string and array functions instead.
You can explode the part after the ? (which you can get using substr to get a substring and strrpos to get the position of the last ?) into an array, and use unset to remove arg3, and then join to put the string back together.:
$string = "http://domain.com/php/doc.php?arg1=0&arg2=1&arg3=0";
$pos = strrpos($string, "?"); // get the position of the last ? in the string
$query_string_parts = array();
foreach (explode("&", substr($string, $pos + 1)) as $q)
{
list($key, $val) = explode("=", $q);
if ($key != "arg3")
{
// keep track of the parts that don't have arg3 as the key
$query_string_parts[] = "$key=$val";
}
}
// rebuild the string
$result = substr($string, 0, $pos + 1) . join($query_string_parts);
See it in action at http://www.ideone.com/PrO0a
preg_replace("arg3=[^&]*(&|$)", "", $string)
I'm assuming the url itself won't contain arg3= here, which in a sane world should be a safe assumption.
$new = preg_replace('/&arg3=[^&]*/', '', $string);
This should also work, taking into account, for example, page anchors (#) and at least some of those "weird characters" you mention but don't seem worried about:
function remove_query_part($url, $term)
{
$query_str = parse_url($url, PHP_URL_QUERY);
if ($frag = parse_url($url, PHP_URL_FRAGMENT)) {
$frag = '#' . $frag;
}
parse_str($query_str, $query_arr);
unset($query_arr[$term]);
$new = '?' . http_build_query($query_arr) . $frag;
return str_replace(strstr($url, '?'), $new, $url);
}
Demo:
$string[] = 'http://domain.com/php/doc.php?arg1=0&arg2=1&arg3=0';
$string[] = 'http://domain.com/php/doc.php?arg1=0&arg2=1';
$string[] = 'http://domain.com/php/doc.php?arg1=0&arg2=1&arg3=0#frag';
$string[] = 'http://domain.com/php/doc.php?arg1=0&arg2=1&arg3=0&arg4=4';
$string[] = 'http://domain.com/php/doc.php';
$string[] = 'http://domain.com/php/doc.php#frag';
$string[] = 'http://example.com?arg1=question?mark&arg2=equal=sign&arg3=hello';
foreach ($string as $str) {
echo remove_query_part($str, 'arg3') . "\n";
}
Output:
http://domain.com/php/doc.php?arg1=0&arg2=1
http://domain.com/php/doc.php?arg1=0&arg2=1
http://domain.com/php/doc.php?arg1=0&arg2=1#frag
http://domain.com/php/doc.php?arg1=0&arg2=1&arg4=4
http://domain.com/php/doc.php
http://domain.com/php/doc.php#frag
http://example.com?arg1=question%3Fmark&arg2=equal%3Dsign
Tested only as shown.

Categories