tags:

views:

5124

answers:

4

Hello,

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

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

to be:

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

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

Thanks!

+1  A: 
$str = preg_replace('/\?\//', '?', $str);

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

eyelidlessness
Thanks, that's perfect.
Zero Cool
A: 

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.

Henrik Paul
Er, what if $urlString[$i+1] isn't /?
eyelidlessness
looping through the string char by char is bad coding mate.
MDCore
eyelidlessness: the problem didn't present that case, so neither did my solution take it into account.MDCore: please elaborate, why so?
Henrik Paul
I've run into a problem where it's useful. If your string is on the order of megs in size (it can happen), running preg_replace or str_replace will risk hitting your php.ini's memory_limit. The pcre_replace code in php always mallocs 2x your string size before doing anything, so it can be an issue.
firebird84
Going from my previous comment, if your string is really huge, you can do some strpos tricks to find the right pieces, preg_match them, and then use the above bracket notation to eliminate the characters you don't want. Use with care, since it's not fast, but it will save memory.
firebird84
+13  A: 

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&amp;m=index&amp;t=care";
$goodUrl = str_replace('?/', '?', $badUrl);
CMS
You've got my vote.
eyelidlessness
Thanks eyelidlessness ;)
CMS
A: 
$splitPos = strpos($url, "?/");
if ($splitPos !== false) {
    $url = substr($url, 0, $splitPos) . "?" . substr($url, $splitPos + 2);
}
nickf