I've been working with this code
<?php
class PerchTemplateFilter_sol_en_cat_path extends PerchTemplateFilter {
public function filterAfterProcessing($value, $valueIsMarkup = false) {
// ORIGINAL STRING: solutions-en/rail-technologies/track-components/name-of-product
$mystring = $value;
$replace = ['solutions-en', '%2F'];
$str = '';
$oldstr = str_replace($replace, $str, $mystring);
$str_to_insert = 'XXX';
$findme = '/';
$pos = strpos($mystring, $findme); // I NEED THIS TO INSERT $str_to_insert AFTER THE SECOND FORWARD SLASH FOUND IN THE ORIGINAL STRING?
$value = substr_replace($oldstr, $str_to_insert, $pos, 0);
return $value;
// $value: /rail-technologies/track-components/XXX/name-of-product
// Insert string at specified position
// https://stackoverflow.com/questions/8251426/insert-string-at-specified-position
}
}
PerchSystem::register_template_filter('sol_en_cat_path', 'PerchTemplateFilter_sol_en_cat_path');
?>
My string is: solutions-en/rail-technologies/track-components/name-of-product
I want to end up with: /rail-technologies/XXX/track-components/name-of-product
XXX is only a placeholder value
I guess I need to do something with $pos to set where I want XXX to be added to the string.
I need to insert after the second forward slash, as the string may contain different text
The code above outputs this string: /rail-technoXXXlogies/track-components/ewosr-switch-lock
I can't seem to figure out how to insert XXX after the second forward slash.
Hope someone can provide some help.
How about explode to array, then implode the first two items.
Join with xxx and implode the rest?
function AddInTheMiddle($start, $where, $what){
$arr = explode("/", $what);
$str = implode("/", array_splice($arr,$start,$where)) . '/xxx/' . implode("/", $arr);;
return $str;
}
$str = 'solutions-en/rail-technologies/track-components/name-of-product';
$str = AddInTheMiddle(1, 2, $str);
https://3v4l.org/m98io
Thank you Andreas, your post gave me the nudge I needed. I did this in the end.
// ORIGINAL $value: solutions-en/rail-technologies/track-components/name-of-product
$str = explode("/", $value);
$value = $str[1] . '/' . 'solutions' . '/' . $str[2] . '/';
return $value;
// Removed: solutions-en
// Added: solutions
// $value: rail-technologies/solutions/track-components/name-of-product
I was able to add the name-of-product to the end of the new string elsewhere in my template.
What is the most efficient pattern to replace dots in dot-separated string to an array-like string e.g x.y.z -> x[y][z]
Here is my current code, but I guess there should be a shorter method using regexp.
function convert($input)
{
if (strpos($input, '.') === false) {
return $input;
}
$input = str_replace_first('.', '[', $input);
$input = str_replace('.', '][', $input);
return $input . ']';
}
In your particular case "an array-like string" can be easily obtained using preg_replace function:
$input = "x.d.dsaf.d2.d";
print_r(preg_replace("/\.([^.]+)/", "[$1]", $input)); // "x[d][dsaf][d2][d]"
From what I can understand from your question; "x.y.z" is a String and so should "x[y][z]" be, right?
If that is the case, you may want to give the following code snippet a try:
<?php
$dotSeparatedString = "x.y.z";
$arrayLikeString = "";
//HERE IS THE REGEX YOU ASKED FOR...
$arrayLikeString = str_replace(".", "", preg_replace("#(\.[a-z0-9]*[^.])#", "[$1]", $dotSeparatedString));
var_dump($arrayLikeString); //DUMPS: 'x[y][z]'
Hope it helps you, though....
Using a fairly simple preg_replace_callback() that simply returns a different replacement for the first occurrence of . compared to the other occurrences.
$in = "x.y.z";
function cb($matches) {
static $first = true;
if (!$first)
return '][';
$first = false;
return '[';
}
$out = preg_replace_callback('/(\.)/', 'cb', $in) . ((strpos('.', $in) !== false) ? ']' : ']');
var_dump($out);
The ternary append is to handle the case of no . to replace
already answered but you could simply explode on the period delimiter then reconstruct a string.
$in = 'x.y.z';
$array = explode('.', $in);
$out = '';
foreach ($array as $key => $part){
$out .= ($key) ? '[' . $part . ']' : $part;
}
echo $out;
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);
}
I have some links in a Powerpoint presentation, and for some reason, when those links get clicked, it adds a return parameter to the URL. Well, that return parameter is causing my Joomla site's MVC pattern to get bungled.
What's an efficient way to strip off this return parameter using PHP?
Example:
http://mydomain.example/index.php?id=115&Itemid=283&return=aHR0cDovL2NvbW11bml0
The safest "correct" method would be:
Parse the url into an array with parse_url()
Extract the query portion, decompose that into an array using parse_str()
Delete the query parameters you want by unset() them from the array
Rebuild the original url using http_build_query()
Quick and dirty is to use a string search/replace and/or regex to kill off the value.
In a different thread Justin suggests that the fastest way is to use strtok()
$url = strtok($url, '?');
See his full answer with speed tests as well here: https://stackoverflow.com/a/1251650/452515
This is to complement Marc B's answer with an example, while it may look quite long, it's a safe way to remove a parameter. In this example we remove page_number
<?php
$x = 'http://url.example/search/?location=london&page_number=1';
$parsed = parse_url($x);
$query = $parsed['query'];
parse_str($query, $params);
unset($params['page_number']);
$string = http_build_query($params);
var_dump($string);
function removeParam($url, $param) {
$url = preg_replace('/(&|\?)'.preg_quote($param).'=[^&]*$/', '', $url);
$url = preg_replace('/(&|\?)'.preg_quote($param).'=[^&]*&/', '$1', $url);
return $url;
}
parse_str($queryString, $vars);
unset($vars['return']);
$queryString = http_build_query($vars);
parse_str parses a query string, http_build_query creates a query string.
Procedural Implementation of Marc B's Answer after refining Sergey Telshevsky's Answer.
function strip_param_from_url($url, $param)
{
$base_url = strtok($url, '?'); // Get the base URL
$parsed_url = parse_url($url); // Parse it
// Add missing {
if(array_key_exists('query',$parsed_url)) { // Only execute if there are parameters
$query = $parsed_url['query']; // Get the query string
parse_str($query, $parameters); // Convert Parameters into array
unset($parameters[$param]); // Delete the one you want
$new_query = http_build_query($parameters); // Rebuilt query string
$url =$base_url.'?'.$new_query; // Finally URL is ready
}
return $url;
}
// Usage
echo strip_param_from_url( 'http://url.example/search/?location=london&page_number=1', 'location' )
You could do a preg_replace like:
$new_url = preg_replace('/&?return=[^&]*/', '', $old_url);
Here is the actual code for what's described above as the "the safest 'correct' method"...
function reduce_query($uri = '') {
$kill_params = array('gclid');
$uri_array = parse_url($uri);
if (isset($uri_array['query'])) {
// Do the chopping.
$params = array();
foreach (explode('&', $uri_array['query']) as $param) {
$item = explode('=', $param);
if (!in_array($item[0], $kill_params)) {
$params[$item[0]] = isset($item[1]) ? $item[1] : '';
}
}
// Sort the parameter array to maximize cache hits.
ksort($params);
// Build new URL (no hosts, domains, or fragments involved).
$new_uri = '';
if ($uri_array['path']) {
$new_uri = $uri_array['path'];
}
if (count($params) > 0) {
// Wish there was a more elegant option.
$new_uri .= '?' . urldecode(http_build_query($params));
}
return $new_uri;
}
return $uri;
}
$_SERVER['REQUEST_URI'] = reduce_query($_SERVER['REQUEST_URI']);
However, since this will likely exist prior to the bootstrap of your application, you should probably put it into an anonymous function. Like this...
call_user_func(function($uri) {
$kill_params = array('gclid');
$uri_array = parse_url($uri);
if (isset($uri_array['query'])) {
// Do the chopping.
$params = array();
foreach (explode('&', $uri_array['query']) as $param) {
$item = explode('=', $param);
if (!in_array($item[0], $kill_params)) {
$params[$item[0]] = isset($item[1]) ? $item[1] : '';
}
}
// Sort the parameter array to maximize cache hits.
ksort($params);
// Build new URL (no hosts, domains, or fragments involved).
$new_uri = '';
if ($uri_array['path']) {
$new_uri = $uri_array['path'];
}
if (count($params) > 0) {
// Wish there was a more elegant option.
$new_uri .= '?' . urldecode(http_build_query($params));
}
// Update server variable.
$_SERVER['REQUEST_URI'] = $new_uri;
}
}, $_SERVER['REQUEST_URI']);
NOTE: Updated with urldecode() to avoid double encoding via http_build_query() function.
NOTE: Updated with ksort() to allow params with no value without an error.
This one of many ways, not tested, but should work.
$link = 'http://mydomain.example/index.php?id=115&Itemid=283&return=aHR0cDovL2NvbW11bml0';
$linkParts = explode('&return=', $link);
$link = $linkParts[0];
Wow, there are a lot of examples here. I am providing one that does some error handling. It rebuilds and returns the entire URL with the query-string-param-to-be-removed, removed. It also provides a bonus function that builds the current URL on the fly. Tested, works!
Credit to Mark B for the steps. This is a complete solution to tpow's "strip off this return parameter" original question -- might be handy for beginners, trying to avoid PHP gotchas. :-)
<?php
function currenturl_without_queryparam( $queryparamkey ) {
$current_url = current_url();
$parsed_url = parse_url( $current_url );
if( array_key_exists( 'query', $parsed_url )) {
$query_portion = $parsed_url['query'];
} else {
return $current_url;
}
parse_str( $query_portion, $query_array );
if( array_key_exists( $queryparamkey , $query_array ) ) {
unset( $query_array[$queryparamkey] );
$q = ( count( $query_array ) === 0 ) ? '' : '?';
return $parsed_url['scheme'] . '://' . $parsed_url['host'] . $parsed_url['path'] . $q . http_build_query( $query_array );
} else {
return $current_url;
}
}
function current_url() {
$current_url = 'http' . (isset($_SERVER['HTTPS']) ? 's' : '') . '://' . "{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";
return $current_url;
}
echo currenturl_without_queryparam( 'key' );
?>
$var = preg_replace( "/return=[^&]+/", "", $var );
$var = preg_replace( "/&{2,}/", "&", $var );
Second line will just replace && to &
very simple
$link = "http://example.com/index.php?id=115&Itemid=283&return=aHR0cDovL2NvbW11bml0"
echo substr($link, 0, strpos($link, "return") - 1);
//output : http://example.com/index.php?id=115&Itemid=283
#MarcB mentioned that it is dirty to use regex to remove an url parameter. And yes it is, because it's not as easy as it looks:
$urls = array(
'example.com/?foo=bar',
'example.com/?bar=foo&foo=bar',
'example.com/?foo=bar&bar=foo',
);
echo 'Original' . PHP_EOL;
foreach ($urls as $url) {
echo $url . PHP_EOL;
}
echo PHP_EOL . '#AaronHathaway' . PHP_EOL;
foreach ($urls as $url) {
echo preg_replace('#&?foo=[^&]*#', null, $url) . PHP_EOL;
}
echo PHP_EOL . '#SergeS' . PHP_EOL;
foreach ($urls as $url) {
echo preg_replace( "/&{2,}/", "&", preg_replace( "/foo=[^&]+/", "", $url)) . PHP_EOL;
}
echo PHP_EOL . '#Justin' . PHP_EOL;
foreach ($urls as $url) {
echo preg_replace('/([?&])foo=[^&]+(&|$)/', '$1', $url) . PHP_EOL;
}
echo PHP_EOL . '#kraftb' . PHP_EOL;
foreach ($urls as $url) {
echo preg_replace('/(&|\?)foo=[^&]*&/', '$1', preg_replace('/(&|\?)foo=[^&]*$/', '', $url)) . PHP_EOL;
}
echo PHP_EOL . 'My version' . PHP_EOL;
foreach ($urls as $url) {
echo str_replace('/&', '/?', preg_replace('#[&?]foo=[^&]*#', null, $url)) . PHP_EOL;
}
returns:
Original
example.com/?foo=bar
example.com/?bar=foo&foo=bar
example.com/?foo=bar&bar=foo
#AaronHathaway
example.com/?
example.com/?bar=foo
example.com/?&bar=foo
#SergeS
example.com/?
example.com/?bar=foo&
example.com/?&bar=foo
#Justin
example.com/?
example.com/?bar=foo&
example.com/?bar=foo
#kraftb
example.com/
example.com/?bar=foo
example.com/?bar=foo
My version
example.com/
example.com/?bar=foo
example.com/?bar=foo
As you can see only #kraftb posted a correct answer using regex and my version is a little bit smaller.
Remove Get Parameters From Current Page
<?php
$url_dir=$_SERVER['REQUEST_URI'];
$url_dir_no_get_param= explode("?",$url_dir)[0];
echo $_SERVER['HTTP_HOST'].$url_dir_no_get_param;
This should do it:
public function removeQueryParam(string $url, string $param): string
{
$parsedUrl = parse_url($url);
if (isset($parsedUrl[$param])) {
$baseUrl = strtok($url, '?');
parse_str(parse_url($url)['query'], $query);
unset($query[$param]);
return sprintf('%s?%s',
$baseUrl,
http_build_query($query)
);
}
return $url;
}
Simple solution that will work for every url
With this solution $url format or parameter position doesn't matter, as an example I added another parameter and anchor at the end of $url:
https://example.com/index.php?id=115&Itemid=283&return=aHR0cDovL2NvbW11bml0&bonus=test#test2
Here is the simple solution:
$url = 'https://example.com/index.php?id=115&Itemid=283&return=aHR0cDovL2NvbW11bml0&bonus=test#test2';
$url_query_stirng = parse_url($url, PHP_URL_QUERY);
parse_str( $url_query_stirng, $url_parsed_query );
unset($url_parsed_query['return']);
$url = str_replace( $url_query_stirng, http_build_query( $url_parsed_query ), $url );
echo $url;
Final result for $url string is:
https://example.com/index.php?id=115&Itemid=283&bonus=test#test2
Some of the examples posted are so extensive. This is what I use on my projects.
function removeQueryParameter($url, $param){
list($baseUrl, $urlQuery) = explode('?', $url, 2);
parse_str($urlQuery, $urlQueryArr);
unset($urlQueryArr[$param]);
if(count($urlQueryArr))
return $baseUrl.'?'.http_build_query($urlQueryArr);
else
return $baseUrl;
}
function remove_attribute($url,$attribute)
{
$url=explode('?',$url);
$new_parameters=false;
if(isset($url[1]))
{
$params=explode('&',$url[1]);
$new_parameters=ra($params,$attribute);
}
$construct_parameters=($new_parameters && $new_parameters!='' ) ? ('?'.$new_parameters):'';
return $new_url=$url[0].$construct_parameters;
}
function ra($params,$attr)
{ $attr=$attr.'=';
$new_params=array();
for($i=0;$i<count($params);$i++)
{
$pos=strpos($params[$i],$attr);
if($pos===false)
$new_params[]=$params[$i];
}
if(count($new_params)>0)
return implode('&',$new_params);
else
return false;
}
//just copy the above code and just call this function like this to get new url without particular parameter
echo remove_attribute($url,'delete_params'); // gives new url without that parameter
I know this is an old question but if you only want to remove one or few named url parameter you can use this function:
function RemoveGet_Regex($variable, $rewritten_url): string {
$rewritten_url = preg_replace("/(\?)$/", "", preg_replace("/\?&/", "?", preg_replace("/((?<=\?)|&){$variable}=[\w]*/i", "", $rewritten_url)));
return $rewritten_url;
}
function RemoveGet($name): void {
$rewritten_url = "https://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
if(is_array($name)) {
for($i = 0; $i < count($name); $i++) {
$rewritten_url = RemoveGet_Regex($name[$i], $rewritten_url);
$is_set[] = isset($_GET[$name[$i]]);
}
$array_filtered = array_filter($is_set);
if (!empty($array_filtered)) {
header("Location: ".$rewritten_url);
}
}
else {
$rewritten_url = RemoveGet_Regex($name, $rewritten_url);
if(isset($_GET[$name])) {
header("Location: ".$rewritten_url);
}
}
}
In the first function preg_replace("/((?<=\?)|&){$variable}=[\w]*/i", "", $rewritten_url) will remove the get parameter, and the others will tidy it up. The second function will then redirect.
RemoveGet("id"); will remove the id=whatever from the url. The function can also work with arrays. For your example,
Remove(array("id","Item","return"));
To strip any parameter from the url using PHP script you need to follow this script:
function getNewArray($array,$k){
$dataArray = $array;
unset($array[$k]);
$dataArray = $array;
return $dataArray;
}
function getFullURL(){
return (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
}
$url = getFullURL();
$url_components = parse_url($url);
// Use parse_str() function to parse the
// string passed via URL
parse_str($url_components['query'], $params);
print_r($params);
<ul>
<?php foreach($params as $k=>$v){?>
<?php
$newArray = getNewArray($params,$k);
$parameters = http_build_query($newArray);
$newURL = $_SERVER['PHP_SELF']."?".$parameters;
?>
<li><?=$v;?> X
<?php }?>
</ul>
here is functions optimized for speed. But this functions DO NOT remove arrays like a[]=x&a[1]bb=y&a[2]=z by array name.
function removeQueryParam($query, $param)
{
$quoted_param = preg_quote($param, '/');
$pattern = "/(^$quoted_param=[^&]*&?)|(&$quoted_param=[^&]*)/";
return preg_replace($pattern, '', $query);
}
function removeQueryParams($query, array $params)
{
if ($params)
{
$pattern = '/';
foreach ($params as $param)
{
$quoted_param = preg_quote($param, '/');
$pattern .= "(^$quoted_param=[^&]*&?)|(&$quoted_param=[^&]*)|";
}
$pattern[-1] = '/';
return preg_replace($pattern, '', $query);
}
return $query;
}
<? if(isset($_GET['i'])){unset($_GET['i']); header('location:/');} ?>
This will remove the 'i' parameter from the URL. Change the 'i's to whatever you need.
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.