使用 preg_replace 删除某些字符周围的空格 [英] Remove whitespace around certain character with preg_replace
本文介绍了使用 preg_replace 删除某些字符周围的空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个字符串,我想使用 preg_replace 删除某个字符周围的所有空格.在我的例子中,这个字符是 /
.
I have a string where I want to remove all the whitespace around a certain character using preg_replace. In my case this character is /
.
例如:
第一部分/第二部分
会变成第一部分/第二部分
或者假设字符是 :
现在:
Or let's say that character is :
now:
第一部分:第二部分
会变成第一部分:第二部分
我找不到有关如何执行此操作的示例...谢谢!
I couldn't find an example on how to do this... Thanks!
推荐答案
$string = preg_replace("/\s*([\/:])\s*/", "$1", $string);
说明:
\s*
表示任意数量(*
)的空格(\s
)[\/:]
是/
或:
.如果您想要其他角色,只需在此处添加即可.- 括号是一个捕获组,您用
$1
引用它,这意味着如果它与:
匹配,那么 $1 将表示:
.
\s*
means any amount (*
) of whitespace (\s
)[\/:]
is either a/
or a:
. If you want another character, just add it here.- the brackets are a capture group which you reference with the
$1
meaning that if it matches a:
then the $1 will mean:
.
这篇关于使用 preg_replace 删除某些字符周围的空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文