Find if text not in ()

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
User avatar
Skara
Forum Regular
Posts: 703
Joined: Sat Mar 12, 2005 7:13 pm
Location: US

Find if text not in ()

Post by Skara »

valid:
(some text and stuff), (some other text), (something else)(something else)
invalid:
(something) something else, (something)

I need to find if anything other than a comma is outside () in a line of text.
After playing a little bit, I think this is beyond me. Help?

Thanks.
User avatar
prometheuzz
Forum Regular
Posts: 779
Joined: Fri Apr 04, 2008 5:51 am

Re: Find if text not in ()

Post by prometheuzz »

Skara wrote:valid:
(some text and stuff), (some other text), (something else)(something else)
invalid:
(something) something else, (something)

I need to find if anything other than a comma is outside () in a line of text.
After playing a little bit, I think this is beyond me. Help?

Thanks.
Here's a way:

Code: Select all

<?php
function test($text) {
  if(preg_match_all('/[^,()\s](?=[^()]*(?:\(|$))/', $text, $matches)) {
    echo "Invalid character(s): ";
    print_r($matches);
  } else {
    echo 'OK!';
  }
}
test('(some text and stuff), a (some other text), b (something else)c(something else)d');
test('(some text and stuff), (some other text), (something else)(something else)');
 
/*
     
[^,()\s]       # match any character except ',', '(', ')' or a white space character
(?=            # start positive look ahead
  [^()]*       #   zero or more characters of any type, except parenthesis
  (?:\(|$)     #   followed by either a '(', or the end of the line/string
)              # stop look ahead
 
*/
?>
And the following regex is perhaps a bit less intuitive, but does the same thing:

Code: Select all

'/[^,()\s](?![^()]*\))/'
This last regex in plain English would be: "match any character other than a comma, parenthesis or a white space character, only if it does not have zero or more characters other than parenthesis in front of it, followed by an opening parenthesis (in other words: match a certain character only if it's not inside parenthesis)".
User avatar
Skara
Forum Regular
Posts: 703
Joined: Sat Mar 12, 2005 7:13 pm
Location: US

Re: Find if text not in ()

Post by Skara »

oi. thanks. saves me much hassle.
Post Reply