Find all occurrences of a substring in a string with PHP
August 25th, 2013 14,311
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.