正则表达式转义特定字符

发布于 2024-11-17 22:08:50 字数 440 浏览 2 评论 0原文

我正在使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

伴梦长久 2024-11-24 22:08:50

[] 被解释为字符类,因此其中的任何字符都匹配。尝试这个,但不要对其进行拆分,使用 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 \ like this\*value, you can split on this regex:

(?<!\\)\*
琴流音 2024-11-24 22:08:50

你当前的正则表达式有点……狂野。字符类中的大多数特殊字符都按字面意思处理,因此可以大大简化:

$str = "{Some:Value*Here}";
$result = preg_split("/[{}:]+/", $str, -1, PREG_SPLIT_NO_EMPTY);

现在 $result 看起来像这样:

array(2) {
  [0] => string(4) "Some"
  [1] => string(10) "Value*Here"
}

Your current regular expression is a little... wild. Most special characters inside a character class are treated literally, so it can be greatly simplified:

$str = "{Some:Value*Here}";
$result = preg_split("/[{}:]+/", $str, -1, PREG_SPLIT_NO_EMPTY);

And now $result looks like this:

array(2) {
  [0] => string(4) "Some"
  [1] => string(10) "Value*Here"
}
旧故 2024-11-24 22:08:50

解决您的问题的正确且最安全的解决方案是使用 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 to str_replace them back after quoting.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文