find all occurrence of a string

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
ofir0803
Forum Newbie
Posts: 22
Joined: Sun Jan 18, 2009 3:03 pm

find all occurrence of a string

Post by ofir0803 »

i want to find all occurrence of a string: "coords"" within another, but i only can found the first and the last
( stripos() and strripos() )

Code: Select all

<body>  
<img src="page.jpg" border="0" usemap="#fghf"  />
<map name="fghf" id="fghf">
<area shape="rect" coords="10,71,258,236" href="#" alt="some_alt" title="some_title" />
<area shape="rect" coords="258,72,506,237" href="#" alt="some_alt" title="some_title" />
<area shape="rect" coords="155,79,150,200" href="#" alt="some_alt" title="some_title" />
<area shape="rect" coords="88,22,400,217" href="#" alt="some_alt" title="some_title" />
</map> 
</body>

i have manage to extract one of them:

Code: Select all

//get coords
	$pos = strpos($file,"coords=\"");
	$tmpfile = substr($file,$pos+8);
	list($tmpfile) = split(" ",$tmpfile);
	$tmpfile_len = strlen($tmpfile);
	$coords = substr($tmpfile,0,$tmpfile_len-1);
how can i loop on all the strings:"coords" ?
User avatar
Zyxist
Forum Contributor
Posts: 104
Joined: Sun Jan 14, 2007 10:44 am
Location: Cracow, Poland

Re: find all occurrence of a string

Post by Zyxist »

Use either preg_match_all() or put strpos() into a loop:

Code: Select all

$offset = 0;
$length = strlen($text);
$searchedLength = strlen($searchedWord);
$found = array();
while($offset < $length)
{
    $test = strpos($text, $searchedWrod, $offset);
    if($test === false)
    {
        break;
    }
    $found[] = $test;
    $offset = $test + $searchedLength;
}
ofir0803
Forum Newbie
Posts: 22
Joined: Sun Jan 18, 2009 3:03 pm

Re: find all occurrence of a string

Post by ofir0803 »

WOW !!

thank's

here is the code:

Code: Select all

$offset = 0;
	$length = strlen($file);
	$searchedLength = strlen("coords");
	$found = array();
	while($offset < $length)
	{
		$test = strpos($file, "coords", $offset);
		if($test === false)
		{
			break;
		}
	$pos = strpos($file,"coords=\"",$offset);
	$tmpfile = substr($file,$pos+8);
	list($tmpfile) = split(" ",$tmpfile);
	$tmpfile_len = strlen($tmpfile);
	$coords = substr($tmpfile,0,$tmpfile_len-1);
	echo $coords;
	
	
	//split the coords
	list($top,$left,$bottom,$right) = split(",",$coords);
	echo "<br/> top:" . $top."px<br/> ";
	echo "left:" . $left."px<br/>";
	echo "bottom:" . $bottom."px<br/>";
	echo "right:" . $right."px<br/>";

		
		$found[] = $test;
		$offset = $test + $searchedLength;
Post Reply