Forum Moderators: coopster

Message Too Old, No Replies

strpos can't find what I specify

         

H2O_aa

5:59 pm on May 26, 2005 (gmt 0)

10+ Year Member



$title = 'The Webmaster World';
$findme = 'c'; //c doesn't exist
$pos = strpos($title, $findme);
print $pos; //this doesn't print anything to the screen
$newtitle = substr("$title", 0 , $pos);
print $newtitle; //this doesn't print anything to the screen either

So if I put the above code in a webpage and run it, I would get an empty screen.

I know if strpos() can't find what I specify, it returns a boolean FALSE. So the substr() will be trying to execute a FALSE variable and thus makes itself FALSE as well and not return anything? Is that how substr() above will interpret this?

Thanks.

jatar_k

6:14 pm on May 26, 2005 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



I would do it this way

$title = 'The Webmaster World';
$findme = 'c';
$pos = strpos($title, $findme);
if ($pos === false) {
echo 'not found';
} else {
$newtitle = substr($title, 0, $pos);
print $newtitle;
}

that way both cases are properly handled

mcibor

8:00 pm on May 26, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



It doesn't matter if substr reads it as false.
Because php disregards datatype, there is no difference to substr if the specified length substr($text, $position, $length) is 0, null, '', or false. It is always interpreted as 0.

You can check if strpos returns false:

if(strpos("The", "c") === false) echo "Returns false";
else "Doesn't return false"; (=== is comparison with datatype)

you can learn more about substr on [php.net...]

Hope it helps
Michal Cibor