vk | php mysqli code | php adodb.connection | xgtatxgt image | PHP show current time | jquery browser detection
 


 

Find all occurrences of a substring in a string with PHP



PHP stripos (or mb-stripos) finds the position of the first occurrence of a (case-insensitive) substring in a string. How to find all occurrences?

Here is a solution:

<?php
/**
 * mb_stripos all occurences
 * based on http://www.php.net/manual/en/function.strpos.php#87061
 *
 * Find all occurrences of a needle in a haystack (case-insensitive, UTF8)
 *
 * @param string $haystack
 * @param string $needle
 * @return array or false
 */
function mb_stripos_all($haystack, $needle) {

	$s = 0;
	$i = 0;

	while(is_integer($i)) {

		$i = mb_stripos($haystack, $needle, $s);

		if(is_integer($i)) {
			$aStrPos[] = $i;
			$s = $i + mb_strlen($needle);
		}
	}

	if(isset($aStrPos)) {
		return $aStrPos;
	} else {
		return false;
	}
}
?>

Your comments are welcomed!

Εγγραφή!
Sign-up for our free email newsletter. Get updates when new tutorials and tips are published. You can unsubscribe anytime with a click.

Your comments are welcomed!

This site actively encourages commenting on any post. Comments are not pre-moderated, but this community does not tolerate direct or indirect attacks, name-calling or insults. Please, read terms of use and Comment Policy at privacy policy.

comments powered by Disqus
More tips