正则表达式转义特定字符
我正在使用 preg_split 来制作具有某些值的数组。 如果我有诸如“This*Value”之类的值,则 preg_split 会将值拆分为 array('This', 'Value') 因为值中的 *,但我想将其拆分到我指定的位置,而不是拆分到* 来自值。如何转义值,使字符串的符号不对表达式生效?
例子:
// Cut into {$1:$2}
$str = "{Some:Value*Here}";
$result = preg_split("/[\{(.*)\:(.*)\}]+/", $str, -1, PREG_SPLIT_NO_EMPTY);
// Result:
Array(
'Some',
'Value',
'Here'
);
// Results wanted:
Array(
'Some',
'Value*Here'
);
I'm using preg_split to make array with some values.
If I have value such as 'This*Value', preg_split will split the value to array('This', 'Value') because of the * in the value, but I want to split it to where I specified, not to the * from the value.How can escape the value, so symbols of the string not to take effect on the expression ?
Example:
// Cut into {$1:$2}
$str = "{Some:Value*Here}";
$result = preg_split("/[\{(.*)\:(.*)\}]+/", $str, -1, PREG_SPLIT_NO_EMPTY);
// Result:
Array(
'Some',
'Value',
'Here'
);
// Results wanted:
Array(
'Some',
'Value*Here'
);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
[
和]
被解释为字符类,因此其中的任何字符都匹配。尝试这个,但不要对其进行拆分,使用 preg_match 并查看匹配的捕获组。原始答案(不适用于OP的问题):
如果您想使用
\
转义值中的*
,例如this\*value
,您可以拆分此正则表达式:The
[
and]
are interpreted as character classes, so any character inside them matches. Try this one, but don't split on it, use preg_match and look in the match's captured groups.Original answer (which does not apply to the OP's problem):
If you want to escape
*
in your values with\
likethis\*value
, you can split on this regex:你当前的正则表达式有点……狂野。字符类中的大多数特殊字符都按字面意思处理,因此可以大大简化:
现在
$result
看起来像这样:Your current regular expression is a little... wild. Most special characters inside a character class are treated literally, so it can be greatly simplified:
And now
$result
looks like this:解决您的问题的正确且最安全的解决方案是使用
preg_quote
。如果字符串包含不应被引号引起来的字符,则需要str_replace
将它们返回引用。The correct and safest solution to your problem is to use
preg_quote
. If the string contains chars that shall not be quoted, you need tostr_replace
them back after quoting.