Topic: More Efficient?
I was working on some code for a BBParser and I had come up with the code below. I looked to see what Rickard came up with, and honestly I think mine is more efficient. Take a look to see if you can benefit from it.
This basically does the same thing as check_tag_order:
<?php
// Returns true if each instance of a end tag has a beginning before it,
// unless count is mismatched.
function compare_strpos($text, $tag){
$ret = TRUE; // Set return value to true, in case it gets past the gauntlet
$begin = strpos_array($text, '[' . $tag); // Retrieve array for tag beginning
$end = strpos_array($text, '[/' . $tag . ']'); // Ditto for end
if (count($begin) != count($end)) { // If the counts don't match, return value is FALSE
$ret = FALSE;
}
foreach ($begin as $count => $pos) { // Check each occurence
if($pos > $end[$count]) $ret = FALSE; // If position of the same occurence count of end tag
} // is before the begin tag, return value is FALSE
return $ret; // Return return value
}
// Returns an array in this fashion:
// array(count => position)
function strpos_array($haystack, $needle){
$kill = 0; // Kills while loop when changed
$offset = 0; // Offset for strpos()
$i = 0; // Counter, not iterator
while ($kill === 0) {
$i++;
$result = strpos($haystack, $needle, $offset);
if ($result === FALSE) { // If result is false (no more instances found), kill the while loop
$kill = 1;
} else {
$array[$i] = $result; // Set array
$offset = $result + 1; // Offset is set 1 character after previous occurence
}
}
return $array;
}
?>
usage
$string = '[quote]blahblah[/quote]
';
compare_strpos($string, 'quote'); // returns true
$string = '[/quote]
blahblah[quote]';
compare_strpos($string, 'quote'); // returns false
$string = '[quote]blahblah';
compare_strpos($string, 'quote'); // returns false
$string = 'blahblah[/quote]
';
compare_strpos($string, 'quote'); // returns false
I hope this helps.