如何使用 PHP 从字符串中删除子字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10771248/
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
How to remove a substring from a string using PHP?
提问by pepe
Given the following string
给定以下字符串
http://thedude.com/05/simons-cat-and-frog-100x100.jpg
I would like to use substror trim(or whatever you find more appropriate) to return this
我想用substr或trim(或任何你觉得更合适的)来返回这个
http://thedude.com/05/simons-cat-and-frog.jpg
that is, to remove the -100x100. All images I need will have that tagged to the end of the filename, immediately before the extension.
也就是说,要删除-100x100. 我需要的所有图像都将标记到文件名的末尾,紧接在扩展名之前。
There appears to be responses for this on SO re Ruby and Python but not PHP/specific to my needs.
在 SO re Ruby 和 Python 上似乎对此有回应,但没有针对我的需求的 PHP/特定。
How to remove the left part of a string?
Remove n characters from a start of a string
Remove substring from the string
Any suggestions?
有什么建议?
回答by Sampson
If you want to match any width/height values:
如果要匹配任何宽度/高度值:
$path = "http://thedude.com/05/simons-cat-and-frog-100x100.jpg";
// http://thedude.com/05/simons-cat-and-frog.jpg
echo preg_replace( "/-\d+x\d+/", "", $path );
Demo: http://codepad.org/cnKum1kd
演示:http: //codepad.org/cnKum1kd
The pattern used is pretty basic:
使用的模式非常基本:
/ Denotes the start of the pattern - Literal - character \d+ A digit, 1 or more times x Literal x character \d+ A digit, 1 or more times / Denotes the end of the pattern
回答by WojtekT
$url = "http://thedude.com/05/simons-cat-and-frog-100x100.jpg";
$new_url = str_replace("-100x100","",$url);
回答by flowfree
$url = str_replace("-100x100.jpg", '.jpg', $url);
Use -100x100.jpgfor bullet-proof solution.
使用-100x100.jpg防弹解决方案。
回答by Norse
If -100x100are the only characters you're trying to remove from all of your strings, why not use str_replace?
如果-100x100是您要从所有字符串中删除的唯一字符,为什么不使用str_replace?
$url = "http://thedude.com/05/simons-cat-and-frog-100x100.jpg";
str_replace("-100x100", "", $url);

