从字符串中删除特定字符的方法? [英] Methods to remove specific characters from string?

查看:99
本文介绍了从字符串中删除特定字符的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从下面的变量值中的$widget_text中删除括号"["和]",并将结果存储在$widget_id中.

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_and-some-text]';
$widget_id = ?;

使用preg_replacestr_replace还是其他?

推荐答案

有几种可用的方法,有时可以使它们执行完全相同的任务,例如preg_replace/str_replace.但是,也许您只想从字符串的开头或结尾删除方括号;在这种情况下,preg_replace可以工作.但是,如果可能有多个括号,则preg_replace也可以完成这项工作.但是修剪更容易,更有意义.

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()-删除开头和结尾的括号

preg_replace() - removes beginning and trailing brackets

$widget_id = preg_replace(array('/^\[/','/\]$/'), '',$widget_text);      

str_replace()-这将删除文本中任何位置的括号

str_replace() - this removes brackets anywhere in the text

$widget_id = str_replace(array('[',']'), '',$widget_text);

trim()-从开头和结尾修剪括号

trim() - trims brackets from beginning and end

$widget_id = trim($widget_text,'[]')

substr()-与trim()相同(假设窗口小部件文本中不包含任何右括号)

substr() - does the same as trim() (assuming the widget text does not include any closing brackets within the text)

$widget_id = substr($widget_text,
                    $start = strspn($widget_text, '['),
                    strcspn($widget_text, ']') - $start
             );

这篇关于从字符串中删除特定字符的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆