$string = 'hi there [hello]this is my hello message[/hello][hello]this is another hello message[/hello]';
// Count the number of occurences:
$count = preg_match_all( '/\\[hello\\]/', $string, $dummy );
// Delete [hello] if not closed
// First replace closed matches, then delete remaining, then replace back
$string = preg_replace( '/\\[hello\\](.*)\\[\\/hello\\]/U', '[qwerty]$1[/qwerty]', $string );
$string = str_replace( '[hello]', '', $string );
$string = str_replace( 'qwerty', 'hello', $string );
echo "Count is: $count$string";
?>
Tuesday, September 15, 2009
PHP counting the # of word occurance in a string
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment