Zero Cool
Zero Cool

Reputation: 1936

PHP removing a character in a string

My php is weak and I'm trying to change this string:

http://www.example.com/backend.php?/c=crud&m=index&t=care
                                   ^

to be:

http://www.example.com/backend.php?c=crud&m=index&t=care
                                  ^

removing the / after the backend.php?. Any ideas on the best way to do this?

Thanks!

Upvotes: 51

Views: 243332

Answers (4)

eyelidlessness
eyelidlessness

Reputation: 63529

$str = preg_replace('/\?\//', '?', $str);

Edit: See CMS' answer. It's late, I should know better.

Upvotes: 8

nickf
nickf

Reputation: 546473

$splitPos = strpos($url, "?/");
if ($splitPos !== false) {
    $url = substr($url, 0, $splitPos) . "?" . substr($url, $splitPos + 2);
}

Upvotes: 0

Christian C. Salvadó
Christian C. Salvadó

Reputation: 828002

I think that it's better to use simply str_replace, like the manual says:

If you don't need fancy replacing rules (like regular expressions), you should always use this function instead of ereg_replace() or preg_replace().

<?
$badUrl = "http://www.site.com/backend.php?/c=crud&m=index&t=care";
$goodUrl = str_replace('?/', '?', $badUrl);

Upvotes: 141

Henrik Paul
Henrik Paul

Reputation: 67723

While a regexp would suit here just fine, I'll present you with an alternative method. It might be a tad faster than the equivalent regexp, but life's all about choices (...or something).

$length = strlen($urlString);
for ($i=0; $i<$length; i++) {
  if ($urlString[$i] === '?') {
    $urlString[$i+1] = '';
    break;
  }
}

Weird, I know.

Upvotes: 0

Related Questions