52

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!

1
  • You should actually mark CMS' answer as the correct one. Commented Nov 5, 2008 at 6:50

4 Answers 4

141

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);
Sign up to request clarification or add additional context in comments.

Comments

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

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

2 Comments

str_replace is blindingly faster than a regex.
@Pestilence, that's why I recommended CMS' answer.
0

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.

5 Comments

Er, what if $urlString[$i+1] isn't /?
eyelidlessness: the problem didn't present that case, so neither did my solution take it into account. MDCore: please elaborate, why so?
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.
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.
This solution looks smart, but if I try it, it gives me an error: "Cannot assign an empty string to a string offset". What could the reason?
0
$splitPos = strpos($url, "?/");
if ($splitPos !== false) {
    $url = substr($url, 0, $splitPos) . "?" . substr($url, $splitPos + 2);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.