Jump to content

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?

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>";
}

?>

  • 4 years later...

DarkWater has written a working function - Rohan Shenoy's procedure doesn't work correctly, unless you add following at the beginning of the loop in the bottom of the code:

if ($i>1)

{

$pos[$i] = $pos[$i]-(1*$i)+1;

}

 

//Sovetryne

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.