Page 1 of 1
Find if text not in ()
Posted: Fri Jan 16, 2009 10:07 am
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.
Re: Find if text not in ()
Posted: Fri Jan 16, 2009 10:31 am
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:
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)".
Re: Find if text not in ()
Posted: Sat Jan 17, 2009 7:05 pm
by Skara
oi. thanks. saves me much hassle.