17

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

Pr0no
  • 3,910
  • 21
  • 74
  • 121
  • Possible duplicate of [Lowercase everything except when between brackets](http://stackoverflow.com/questions/9229030/lowercase-everything-except-when-between-brackets) – hakre Feb 13 '12 at 13:22
  • Related: [*Exclude strings within parentheses from a regular expression?*](https://stackoverflow.com/q/3285510/3357935) – Stevoisiak Jan 06 '23 at 19:05

2 Answers2

21

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);
stema
  • 90,351
  • 20
  • 107
  • 135
  • My mistake - I forgot the requirement that everything that is not between brackets, should be returned lowercase. So, again, what is between brackets is left alone. Is it possible with this regex to return the rest in lowercase? – Pr0no Feb 10 '12 at 00:23
  • I would say, not within the same preg_replace. But in a second step no problem. Check this [link](http://de2.php.net/manual/en/functions.anonymous.php) it should get you started. If you have problems, please ask an new question then. – stema Feb 10 '12 at 07:05
  • This doesn't work in VS Code. "*Invalid regular expression. Lone quantifier brackets.*" – Stevoisiak Jan 06 '23 at 19:03
4
$str = preg_replace('(\{[^}]+\}(*SKIP)(*FAIL)|[^a-zA-Z ]+)', '', $str);

See also Split string by delimiter, but not if it is escaped.

Community
  • 1
  • 1
NikiC
  • 100,734
  • 37
  • 191
  • 225
  • I came to a somewhat [similar conclusion](http://stackoverflow.com/a/9260679/367456) (based on your linked answer ;)) in a (as I now see) duplicate question. – hakre Feb 13 '12 at 13:20
  • Yay, +100 for `(*SKIP)(*F)`!... @Pr0no this is a really useful and interesting technique, [this](http://stackoverflow.com/q/23589174/) explains it in detail. :) – zx81 Jun 25 '14 at 23:51