php 从字符串中删除特定字符的方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5433754/
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
Methods to remove specific characters from string?
提问by Scott B
I need to remove the brackets "[" and "]" from $widget_text
in the variable value below and store the result in $widget_id
.
我需要从$widget_text
下面的变量值中删除括号“[”和“]”并将结果存储在$widget_id
.
$widget_text = '[widget_and-some-text]';
$widget_id = ?;
Use preg_replace
, str_replace
or something else?
使用preg_replace
,str_replace
或其他什么?
回答by Peter Lindqvist
There are several methods available, and they can sometimes be made to perform exactly the same task, like preg_replace/str_replace. But, perhaps you want to remove brackets only from the beginning or end of the string; in which case preg_replace works. But, if there could be several brackets, preg_replace can do the job too. But trim is easier and makes more sense.
有几种方法可用,有时可以使它们执行完全相同的任务,例如 preg_replace/str_replace。但是,也许您只想从字符串的开头或结尾删除括号;在这种情况下 preg_replace 工作。但是,如果可能有几个括号, preg_replace 也可以完成这项工作。但修剪更容易,更有意义。
preg_replace()- removes beginning and trailing brackets
preg_replace()- 删除开头和结尾的括号
$widget_id = preg_replace(array('/^\[/','/\]$/'), '',$widget_text);
str_replace()- this removes brackets anywhere in the text
str_replace()- 这将删除文本中任何地方的括号
$widget_id = str_replace(array('[',']'), '',$widget_text);
trim()- trims brackets from beginning and end
trim()- 从头到尾修剪括号
$widget_id = trim($widget_text,'[]')
substr()- does the same as trim() (assuming the widget text does not include any closing brackets within the text)
substr()- 与 trim() 相同(假设小部件文本在文本中不包含任何右括号)
$widget_id = substr($widget_text,
$start = strspn($widget_text, '['),
strcspn($widget_text, ']') - $start
);
回答by Michiel Pater
$widget_id = str_replace('[', '', str_replace(']', '', $widget_text));
回答by J. Macedo
If the brackets are always at first and last position, use this:
如果括号总是在第一个和最后一个位置,请使用:
$widget_id = substr($widget_text, 1, strlen($widget_text)-2);
I think this is a faster way...
我认为这是一种更快的方法...