PHP remove an excerpt from the URI with regular expression

2

I have the following uri

$uri = "http://www.meudominio.com.br/pagina.php?campo=teste&ordem=2&cor=azul"

How to remove "ordem=2 "from the url above with regular expression, knowing that the value of the order, time can be 2, 3, 4 and etc?

http://www.meudominio.com.br/pagina.php?campo=teste&cor=azul

Could you try this?

$arr_nova_uri = explode("ordem=", $uri);
$nova_uri = $arr_nova_uri[0].substr($arr_nova_uri[1], 2);
    
asked by anonymous 17.10.2016 / 23:04

3 answers

7

Regular expression:

/(?:(\?)|&)ordem=\d+(?(1)(?:&|$)|(&|$))/

Replacement:

$1$2

Code:

$uri   = 'http://www.meudominio.com.br/pagina.php?campo=teste&ordem=2&cor=azul';
$re    = '/(?:(\?)|&)ordem=\d+(?(1)(?:&|$)|(&|$))/';
$subst = '$1$2';

$nova_uri = preg_replace($re, $subst, $uri);

echo $nova_uri;

Result:

http://www.meudominio.com.br/pagina.php?campo=teste&cor=azul
    
17.10.2016 / 23:49
5

In my Github I've created a gist with a function to do operations like this in a reusable way. What's more, I preferred not to use regular expression, as these usually cost more in terms of performance.

This function allows you to remove, replace or add parameters to a particular url. If it already has Query String, it will be replaced or added.

See:

function url_replace_query($url, array $parameters)
{
    $parts = parse_url($url) + [
        'scheme' => 'http',
        'query'  => NULL,
        'path'   => NULL,
    ];
    if (! isset($parts['host'])) return false;
    parse_str($parts['query'], $query);
    $parameters += $query;
    $newQueryString = http_build_query($parameters);
    return $parts['scheme'] . '://' . $parts['host'] . $parts['path'] . '?' . $newQueryString;
}

You can use it like this:

$url_sem_ordem = url_replace_query("http://www.meudominio.com.br/pagina.php?campo=teste&ordem=2&cor=azul", ['ordem' => null])

Result:

'http://www.meudominio.com.br/pagina.php?campo=teste&cor=azul'
    
18.10.2016 / 12:55
0

If the order parameter is alphanumeric, you can use the following example.

Ps. I posted here for the comments do not extend much

Run in link

$re = '/&?ordem=(\d+)?(\w+)?/';
$str = 'pagina.php?campo=teste&ordem=2&cor=azul
pagina.php?ordem=2&campo=teste
pagina.php?ordem=2FFF&campo=teste
pagina.php?ordem=FFF&campo=teste
 ';
$subst = '';
$result = preg_replace($re, $subst, $str);
    
18.10.2016 / 15:08