tags:

views:

37

answers:

2

Using the strpos() function in PHP, how can I echo what strpos() has found? All items that it has found. Thanks

A: 

strpos finds is what you tell it to find, so in essense you're asking this:

$needle="foo";
if (strpos($haystack, $needle)!==false)
{
    echo $needle;
}

Maybe you actually want to do something else?

Paul Dixon
If it does find it, it returns the position its at in the string using 0 based values. So if you asked to find "foo" in "foobar" it will return 0.
Matt
yes, yes it will.
Paul Dixon
A: 

strpos() only returns the first needle found in the haystack. If you need to find all of them, you can do something like this :

$str = "abcabcabc";
$arr = array();
$delChar = 0;

while (($pos = strpos($str, "a")) !== false) {
    $arr[] = $pos + $delChar;
    $delChar += strlen($str) - strlen(substr($str, $pos + 1));
    $str = substr($str, $pos + 1);
}

var_dump($arr);

which prints 0, 3 and 6.

Edit: I just read the comments, I assumed you meant the positions the function found, maybe I was wrong :-p

Vincent Savard