Jump to content

Find all occurences of a string inside of another string...


DarkWater

Recommended Posts

Is there a simple way to do this?  Like, a built-in PHP function?  I couldn't find one in the manual, so I wrote one, but I really wish there was a better way:

<?php
function find_occurences($string, $find) {
if (strpos(strtolower($string), strtolower($find)) !== FALSE) {
	$pos = -1;
	for ($i=0; $i<substr_count(strtolower($string), strtolower($find)); $i++) {
		$pos = strpos(strtolower($string), strtolower($find), $pos+1);
		$positionarray[] = $pos;
	}

	return $positionarray;
}
else {
	return FALSE;
}

}
?>

Anyone?

Link to comment
Share on other sites

I am sorry about the length of the code being longer than yours but right now, this is what I cud think off.  :)

<?php
$string="This is my house. this is my living room. This is my bedroom. This is great!";
$delimiter="This";
$pos=array();

function fao($str,$delim)
//fao stands for Find All Occurences
{
$str_bits=explode(strtolower($delim),strtolower($str));
global $pos;
$local_pos=array();
$counter="-1";
foreach($str_bits as $individual_bit)
{
$local_pos[]=$individual_bit;

if(sizeof($local_pos)>1)
{
$local_pos_length=strlen(implode("",$local_pos))+strlen($delim)+(4*$counter);
}
else
{
$local_pos_length=strlen(implode("",$local_pos));
}
$counter++;
$pos[]=$local_pos_length;
}

global $string;
}
fao($string,$delimiter);
$size=sizeof($pos)-1;
echo "Occurunces were found to start at the following positions(Left most character is considered as at position 0):<br>";
for($i=0; $i<$size; $i++)
{
echo $pos[$i]."<br>";
}

?>

Link to comment
Share on other sites

  • 4 years later...
Guest
This topic is now closed to further replies.
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.