Re: Regex for balanced brackets?

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Jeffrey Sambells wrote:
I came across this method of matching brackets with regex in .NET

http://puzzleware.net/blogs/archive/2005/08/13/22.aspx

but I am wondering if it is possible to do the same in PHP?

I've tried it a bit but I can't seem to get it to work properly. I'm just wondering if I am doing something wrong or if it is just not possible.

Thanks.

here is the code I was playing with:

<?php

$pattern = <<<PATTERN
\{
    (?>
        [^{}]+
        |
        \{ (?P<DEPTH>)
        |
        \} (?P<-DEPTH>)
    )*
    (?(DEPTH)(?!))

\}
PATTERN;

$subject = <<<SUBJECT
test {
    test2 {
        test3
    }
}

test4
{

}
SUBJECT;


preg_match_all("/$pattern/ix",$subject,$matches);

header("content-type: text/plain; ");

var_dump($matches);

?>


- Jeff



~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Jeffrey Sambells
Director of Research and Development
Zend Certified Engineer (ZCE)

We-Create Inc.
jeff@xxxxxxxxxxxx email
519.745.7374 office
519.897.2552 mobile

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Get Mozilla Firefox at
http://spreadfirefox.com

If I'm understanding what you want, consider this.  I use it to check matching tags.

First get an array of all the start tags:

$pattern= "%<([^/][a-z_\-]*)>%i";		//all start tags used <xxx>

preg_match_all("$pattern", $text_str, $matches);

$start_tags= $matches[1];

$start_tag_nums= array_count_values($start_tags);	//get count for each tag

Then do the same for your end tags, using the same pattern but with the end tag slash. </....

Finally, you make a text list of the mismatches:

foreach($start_tag_nums as $tag=> $num){
		
	if($num != $end_tag_nums[$tag])	$end_error_msg .= "&lt;$tag&gt; || ";
	
}//end foreach
	
echo $end_error_msg;

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux