php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #41013 strstr() and stristr() cannot find zero
Submitted: 2007-04-06 19:04 UTC Modified: 2007-04-07 09:55 UTC
Votes:1
Avg. Score:1.0 ± 0.0
Reproduced:0 of 1 (0.0%)
From: phraje at gmail dot com Assigned:
Status: Not a bug Package: Unknown/Other Function
PHP Version: 5.2.1 OS: linux 2.6.18 & win32
Private report: No CVE-ID: None
 [2007-04-06 19:04 UTC] phraje at gmail dot com
Description:
------------
If a haystack string has a zero (0) as its last character, and the needle is zero, neither strstr() or stristr() will match it.  Can be worked around by concatenating a trailing space to the haystack string.

Reproduce code:
---------------
$haystack="this is a string that ends in 0";
$needle=sprintf("%d",0);

if(strstr($haystack,$needle)) { printf("%s.\n",$haystack); }
if(stristr($haystack,$needle)) { printf("%s.\n",$haystack); }

$haystack="this is a string that doesn't end in 0 ";

if(strstr($haystack,$needle)) { printf("%s.\n",$haystack); }
if(stristr($haystack,$needle)) { printf("%s.\n",$haystack); }

$haystack="this is a string that ends in 1";
$needle=sprintf("%d",1);

if(strstr($haystack,$needle)) { printf("%s.\n",$haystack); }
if(stristr($haystack,$needle)) { printf("%s.\n",$haystack); }


Expected result:
----------------
this is a string that ends in 0.
this is a string that ends in 0.
this is a string that doesn't end in 0 .
this is a string that doesn't end in 0 .
this is a string that ends in 1.
this is a string that ends in 1.


Actual result:
--------------
this is a string that doesn't end in 0 .
this is a string that doesn't end in 0 .
this is a string that ends in 1.
this is a string that ends in 1.

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2007-04-07 00:51 UTC] webmaster at wiedmann-online dot de
In the first two cases strtr() or stristr() returns the string "0".
A loose boolean comparisons with "0" is FALSE and so the if statement is not executed.

In your case you can change the code to:
if(false !== strstr($haystack,$needle)) { printf("%s.\n",$haystack); }

BTW: better use strpos() in this case.
 [2007-04-07 09:55 UTC] johannes@php.net
.
 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Thu Jul 03 07:01:35 2025 UTC