Str_replace does not replace - php

I have variables that gets url. Then from this url I remove another url. First url removes another url but second not because it contains Russians words. How I can remove from url Russians letters:
$url = $_SERVER['REQUEST_URI'];
$url2 = $_SERVER['REQUEST_URI'];
if (isset($_GET['page'])) {
page = $_GET['page'];
}
if (isset($_GET['category'])) {
$category = $_GET['category'];
}
$url = str_replace('&page='.$page, "", $url); // works
$url2 = str_replace('&category='.$category, "", $url2); // does not working
echo $url2; // i check and $url2 does not remove category, because it contains Russians words

With the help of http_build_query (or its polyfill) in your environment, you can write a simple function to rewrite query parameters on the fly instead of using str_replace.
For example, to rewrite the "category" parameter, you may
<?php
function uri_rewrite_query($uri, $callback) {
$parsed = parse_url($uri);
parse_str($parsed['query'] ?? '', $query);
$parsed['query'] = http_build_query($callback($query));
return http_build_url($uri, $parsed);
}
function query_remove_category($query) {
unset($query['category']);
return $query;
}
function query_replace_category($category) {
return function ($query) use ($category) {
$query['category'] = $category;
return $query;
};
}
Then you can do these:
<?php
$uri = '/beverages.php?lang=ru&category=some_category';
echo uri_rewrite_query($uri, 'remove_category');
// Result: /beverages.php?lang=ru
echo uri_rewrite_query($uri, query_replace_category('Безалкогольные напитки'));
// Result: /beverages.php?lang=ru&category=%D0%91%D0%B5%D0%B7%D0%B0%D0%BB%D0%BA%D0%BE%D0%B3%D0%BE%D0%BB%D1%8C%D0%BD%D1%8B%D0%B5+%D0%BD%D0%B0%D0%BF%D0%B8%D1%82%D0%BA%D0%B8 (equivalant to "/beverages.php?lang=ru&category=Безалкогольные напитки")
Or if you're only interested in the query string:
function uri_get_query() {
$parsed = parse_url($uri);
parse_str($parsed['query'] ?? '', $query);
return $query;
}
echo '/food.php?' . http_build_query(query_remove_category($_SERVER['QUERY_STRING'] ?? ''));
echo '/food.php?' . http_build_query(query_replace_category('Безалкогольные напитки')($_SERVER['QUERY_STRING'] ?? ''));

Try searching for the occurrence of the string using urlencode on str_replace(), like so:
$url2 = str_replace('&category='. urlencode($category), "", $url2);

Related

preg_replace with callback not replacing?

I have this function to replace a text with an url to url link.
The callback is used to check if it has http or not in the link, if it has not, add http on it:
<?php
function toLink($titulo){
$url = '~(?:(https?)://([^\s<]+)|(www\.[^\s<]+?\.[^\s<]+))(?<![\.,:])~i';
$titulo = preg_replace_callback($url, function($matches) {
$url = $matches[0];
if (!preg_match('/^https?:\/\//', $url)) {
$url = 'http://'.$matches[0];
$url = '<a href="'.$url.'" target="_blank"
title="'.$url.'">'.$url.'</a>';
}
},$titulo);
return $titulo;
}
echo toLink("hi from www.google.com");
The return value is hi from where is my link?
Your callback needs to return the string (or value) that should be inserted.
This gives you more information.
As mentioned in the comments, the callback function must return a value, to make this fully work. To tie things together, you just need a return $url statement in the end of the callback, like this:
function toLink($titulo){
$url = '~(?:(https?)://([^\s<]+)|(www\.[^\s<]+?\.[^\s<]+))(?<![\.,:])~i';
$titulo = preg_replace_callback($url, function($matches) {
$url = $matches[0];
if (!preg_match('/^https?:\/\//', $url)) {
$url = 'http://'.$matches[0];
$url = '<a href="'.$url.'" target="_blank"
title="'.$url.'">'.$url.'</a>';
}
return $url; // <---- return the $url
},$titulo);
return $titulo;
}
echo toLink("hi from www.google.com");
Check the result on https://eval.in/1079110

PHP function to remove specified variables in a URL

I have created this function to remove specific variables from a string
if(!function_exists("remove_variable")) {
function remove_variable($remove = array(), $url) {
if($url == '') {
$url = $_SERVER["REQUEST_URI"];
}
foreach($remove as $r) {
echo $r.'<br>';
$url = preg_replace('/([?&])'.$r.'=[^&]+(&|$)/','$1', $url);
echo $url.'<br><br>';
}
return $url;
}
}
I am testing with:
<?php echo remove_variable(array("productsearch_name", "productsearch_type", "productsearch_supplier"), $_SERVER["REQUEST_URI"].uri_glue()); ?>
Which is returning:
productsearch_name
/companies/customers/pricelist?productsearch_name=&productsearch_type=Broadband%20&productsearch_supplier=&
productsearch_type
/companies/customers/pricelist?productsearch_name=&productsearch_supplier=&
productsearch_supplier
/companies/customers/pricelist?productsearch_name=&productsearch_supplier=&
/companies/customers/pricelist?productsearch_name=&productsearch_supplier=&
So it is not removing the variables as expected
You can achieve this way,
$str = "http://google.com/companies/customers/pricelist?productsearch_name=asd&productsearch_type=Broadband%20&productsearch_supplier=test";
parse_str(parse_url($str)['query'],$output);
print_r($output);
parse_str — Parses the string into variables.
parse_url — Parse a URL and return its components
I hope this will solve your problem.

PHP to get element from link

I have below code:-
$link = 'http://www.domain.com/go.php?id=545&url=http://www.example.com/about
I want URL element that is - http://www.example.com/about
You can use PHP's inbuilt parse_url and parse_str functions.
$link = 'http://www.domain.com/go.php?id=545&url=http://www.example.com/about';
parse_str(parse_url($link,PHP_URL_QUERY),$url);
echo $url['url'];
$link = 'http://www.domain.com/go.php?id=545&url=http://www.example.com/about';
$url = explode("&url=", $link)[1];
echo $url; //http://www.example.com/about
Try this:
$link = 'http://www.domain.com/go.php?id=545&url=http://www.example.com/about';
$uri=explode("url=",$link);
$uri=$uri[count($uri)-1];
echo $uri;
function getSomething($url) {
if (!(strpos($url, 'url=') !== false)) return false;
$parse = explode('url=', $url);
$code = $parse[1];
return $code;
}
echo getSomething("http://www.domain.com/go.php?id=545&url=http://www.example.com/about");
this will work even if url is placed somewhere else as parameter
$link = 'http://www.domain.com/go.php?id=545&url=http://www.example.com/about';
$url = "";
$params = explode("&", $link);
for($params as $param){
if(substr($param, 0, 4) === 'url='){
$url = explode("=", $param)[1];
break;
}
}
echo $url; //http://www.example.com/about

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];

Strip off specific parameter from URL's querystring

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.

Categories