note 9405 deleted from function.preg-match-all by sniper

From: Date: Tue, 30 Sep 2003 12:22:24 +0000
Subject: note 9405 deleted from function.preg-match-all by sniper
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-57428@lists.php.net to get a copy of this message
Note Submitter: teddk@box100.com ---- I've struggled with regular expression for some time now, and more specifically I've struggled with "greedy" matches. As part of a template project, I wanted to be able to extract out of a string (aka., HTML code) any instances of characters surrouned by the "{}" brackets, i.e. "{PAGETITLE}". To place all the instances of text surrounded by the "{}" in an array named $tags[0] use the following: <?php $text = "I am an HTML file with special tags such as {tag1} and {tag2} in it"; preg_match_all( '/\{.*?\}/', $text, $tags ); foreach ($tags[0] as $loop_result) { echo $loop_result."<br>"; } ?> A simple modification of the expression: (preg_match_all( '/<.*?>/', $text, $tags ) pulls out an array of tags marked with "<>", aka. html tags. Here is an explanation. The "/" marks the begining of the expression. The "\" says do not use the special meaning of the next character. The "{" says find "{". The "." says find any character. The "*" says find zero or more of the previous character (which was any character). The "?" says don't be "greedy," which means match as few characters as possible before the next element in the match. The "\" says do not use the special meaning of the next character. The "}" says find "}". And the "/" marks the end. If you don't use the "?" you get a "greedy" match of everything from the first "{" to the last "}", "{tag1} and {tag2}" Although I've used several sources of info. The best so far has been the Python tutorial at: http://www.python.org/doc/howto/regex/regex.html

« previous php.notes (#57428) next »