Joe
Joe

Reputation: 15

How to detect whether a part of string is inside a quote pair in PHP?

Wondering any regular expression can do that, e.g. I want to find whether foo is inside a quote pairs (no matter single or double quote):

"foo" <- true
"'foo'" <- true
"it's foo" <- true
"abc". Foo. "def" <- false
abc'foo <- false
f"oo" <- false

Upvotes: 0

Views: 108

Answers (1)

Jakub Hampl
Jakub Hampl

Reputation: 40573

In general, no. This kind of stuff is not in the domain of regular languages as you need some sort of memory to track the occurrences of quotes.

However modern regexps are more powerful then simple regular languages, so it might be possible. But I'd go for something like this:

  1. loop through each letter, if you see a quote then flip a boolean variable
  2. if you see foo and the variable is true, continue, otherwise return false
  3. if you then see a quote return true

Use more then a boolean if you care about single and double quotes.

Upvotes: 1

Related Questions