msgbartop
Adam Palmer MBCS CITP, Linux, PHP Programmer, MySQL Developer, Embedded Hardware, Security Consultant
Did my blog help you? Please link to me!
  dns test
 
RSS Feed
msgbarbottom

20 Nov 09 PHP Programmer – strpos, finding the position of a word in a string

In PHP, we can use strpos to find the position of a character or string within another string:

int strpos  ( string $haystack  , mixed $needle  [, int $offset = 0  ] )

For example:

<?php
$mystr = “this is a test string”;
$pos = strpos($mystr, “test”);
echo “Position: ” . $pos;
?>

Returns:  Position: 10

We can just as easily use strpos to test for whether or not a given string is found in a larger string:

if (strpos($mystr, “test”))
{ … }

However, that may in some cases unexpectedly fail:

if (strpos($mystr, “this”))
{ … }

This will return 0, as “this” is at the beginning of the string and therefore at position 0, causing the condition to fail. The correct usage is:

if (strpos($mystr, “this”) === false) { … } OR  if (strpos($mystr, “this”) !== false) { … } noting the usage of “===” or “!==” meaning an absolute evaluation. As of PHP 4, “==” means “equal to” and “===” means “identical to”.

Tags: , ,



Leave a Comment