Consider the following string:
I have been driving to {Palm.!.Beach:100} and it . was . great!!
I use the following regex to delete all punctuation:
$string preg_replace('/[^a-zA-Z ]+/', '', $string);
This outputs:
I have been driving to PalmBeach and it was great!!
But I need the regex to always ignore whatever is in between { and }. So the desired output would be:
I have been driving to {Palm.!.Beach:100} and it was great
How can I let the regex ignore what is between { and }?
If an opening bracket or brace is interpreted as a metacharacter, the regular expression engine interprets the first corresponding closing character as a metacharacter. If this is not the desired behavior, the closing bracket or brace should be escaped by explicitly prepending the backslash (\) character.
In other words, square brackets match exactly one character. (a-z0-9) will match two characters, the first is one of abcdefghijklmnopqrstuvwxyz , the second is one of 0123456789 , just as if the parenthesis weren't there. The () will allow you to read exactly which characters were matched.
$ means "Match the end of the string" (the position after the last character in the string). Both are called anchors and ensure that the entire string is matched instead of just a substring.
Well, you can just add them to the regex with something like [0-9. \)\(-]+ but, since you're complicating the expression, you'll probably need to check for balance as well. In other words, that regex is quite happy to accept 74.7((((((((((((2) which is not really well-formed.
Try this
[^a-zA-Z {}]+(?![^{]*})
See it here on Regexr
Means match anything that is not included in the negated character class, but only if there is no closing bracket ahead without a opening before, this is done by the negative lookahead (?![^{]*})
.
$string preg_replace('/[^a-zA-Z {}]+(?![^{]*})/', '', $string);
$str = preg_replace('(\{[^}]+\}(*SKIP)(*FAIL)|[^a-zA-Z ]+)', '', $str);
See also Split string by delimiter, but not if it is escaped.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With