How to remove the last URL bar

Asked

Viewed 403 times

0

Please, how can I remove the bar at the end of the URL. For example, I have these variables with the urls below, but I cannot remove the last bar:

<?php
 
 $url1 = 'http://www.site.com.br/domain1/domanin2/nome/';
 $url2 = 'http://www.site.com/';
 $url3 = 'http//www.site.com/diretorio/paginas/pagina/';

 $substituir = str_replace('/', '', $url1); // substitui todas as barras

I don’t want to overwrite all the/bars of the url, only the last one. When the urls are overwritten I would have:

  http://www.site.com.br/domain1/domanin2/nome
  http://www.site.com
  http//www.site.com/diretorio/paginas/pagina

Please, could someone help me?

1 answer

1


One option is to use rtrim:

$url1 = 'http://www.site.com.br/domain1/domanin2/nome/';
$sem_barra = rtrim($url1, '/');
echo $sem_barra; // http://www.site.com.br/domain1/domanin2/nome

The second parameter indicates which characters should be removed from the end.


Or, if you know that at the end you definitely have a bar, you can use substr:

$sem_barra = substr($url1, 0, -1);

In this case, I take the zero position (from the beginning of the string) and the size -1 indicates that I want to remove 1 character from the end.

Of course you will always remove the last character, whatever it is. If you want to remove only the bar, then prefer to use rtrim.


And of course, the solution over Engineered regex:

$sem_barra = preg_replace('#/$#', '', $url1);

The idea is to see if there is a bar at the end (the bookmark $ indicates the end of the string), and replace with '' (empty string), which is the same as removing.

The difference is that in this case only one end bar is removed if it exists. Already the rtrim remove all bars from the end:

$s = 'abc///';
echo preg_replace('#/$#', '', $s); // "abc//"
echo rtrim($s, '/'); // "abc"

Browser other questions tagged

You are not signed in. Login or sign up in order to post.