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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 21:23:31  来源:igfitidea点击:

Methods to remove specific characters from string?

phpstring

提问by Scott B

I need to remove the brackets "[" and "]" from $widget_textin 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_replaceor something else?

使用preg_replacestr_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...

我认为这是一种更快的方法...