note 73955 deleted from function.preg-match by colder

From: Date: Mon, 18 Jun 2007 18:13:13 +0000
Subject: note 73955 deleted from function.preg-match by colder
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-127574@lists.php.net to get a copy of this message
Note Submitter: legolas558 d0t users dot sf dot net ---- I wanted to match all php tags in a string but I found preg_match_all not to behave correctly: <?php // additional spacing added not to confuse markup highlighters preg_match_all('/<\\?'.'php.*\\?'.'>/i', $content, $m); ?> Returned only the single line php tags: [0]=> array(4) { [0]=> string(23) "<?php doSomething(); ?>" [1]=> string(19) "<?php echo 'something'; ?>" [2]=> string(34) "<?php doSomethingElse();?>" [3]=> string(35) "<?php echo 'something else'; ?>" } So I gave up and wrote this small function: <?php function php_tags($s) { // retrieve all PHP tags from $s // PHP tags gatherer by legolas558 // initialize variables $offset = 0; $tags = array(); // loop till php tags are found while (false !== ($p = strpos($s, '<'.'?php', $offset))) { $p += 6; $et = strpos($s, '?'.'>', $p); // could not find termination tag if ($et===false) break; // add tag to array $tags[] substr($s, $p, $et-$p); // properly increment offset $offset = $et+2; } return $tags; } ?> This function does the job, however if you have used strings containing "<?php" and "?>" in your PHP code tags it will not work.

« previous php.notes (#127574) next »