Using the strpos()
function in PHP, how can I echo what strpos()
has found? All items that it has found. Thanks
views:
37answers:
2
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
2010-10-23 19:16:24
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
2010-10-23 19:23:09
yes, yes it will.
Paul Dixon
2010-10-23 19:25:20
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
2010-10-23 19:23:09