PHP 删除字符串中的一个字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/264480/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP removing a character in a string
提问by Zero Cool
My php is weak and I'm trying to change this string:
我的 php 很弱,我正在尝试更改此字符串:
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?
取出/后backend.php?。关于做到这一点的最佳方法的任何想法?
Thanks!
谢谢!
回答by CMS
I think that it's better to use simply str_replace, like the manual says:
我认为最好使用简单的str_replace,就像手册上说的:
If you don't need fancy replacing rules (like regular expressions), you should always use this function instead of ereg_replace() or preg_replace().
如果您不需要花哨的替换规则(如正则表达式),则应始终使用此函数而不是 ereg_replace() 或 preg_replace()。
<?
$badUrl = "http://www.site.com/backend.php?/c=crud&m=index&t=care";
$goodUrl = str_replace('?/', '?', $badUrl);
回答by eyelidlessness
$str = preg_replace('/\?\//', '?', $str);
Edit: See CMS' answer. It's late, I should know better.
编辑:请参阅 CMS 的回答。晚了,我应该知道的更好。
回答by Henrik Paul
While a regexp would suit here just fine, I'll present you with an alternative method. It mightbe 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.
很奇怪,我知道。
回答by nickf
$splitPos = strpos($url, "?/");
if ($splitPos !== false) {
$url = substr($url, 0, $splitPos) . "?" . substr($url, $splitPos + 2);
}

