msgbartop
I will happily conduct a FREE basic web security scan for any genuine organization interested in my services to point out whether or not I can find vulnerabilities in your application. Just contact me.
Need a PHP Programmer, PHP staff or project manager? Contact me now.
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

You must be logged in to post a comment.