简体   繁体   中英

Regex escape specific characters

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'
);

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:

(?<!\\)\*

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.

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"
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM