Delicious Bookmark this on Delicious Share on Facebook SlashdotSlashdot It! Digg! Digg



PHP : Function Reference : String Functions : stristr

stristr

Case-insensitive strstr (PHP 4, PHP 5)
string stristr ( string haystack, string needle, bool before_needle )

Example 2456. stristr() example

<?php
 $email
= 'USER@EXAMPLE.com';
 echo
stristr($email, 'e'); // outputs ER@EXAMPLE.com
 
echo stristr($email, 'e', true); // outputs US
?>

Example 2457. Testing if a string is found or not

<?php
 $string
= 'Hello World!';
 if(
stristr($string, 'earth') === FALSE) {
   echo
'"earth" not found in string';
 }
// outputs: "earth" not found in string
?>

Example 2458. Using a non "string" needle

<?php
 $string
= 'APPLE';
 echo
stristr($string, 97); // 97 = lowercase a
// outputs: APPLE
?>

Code Examples / Notes » stristr

triadsebas

You can use strstr() or strstri() to validate data!
Check this out:
<?php
function validate_email($input) {
if (!strstri($input, '@')) {
return false;
}
return true;
}
function validate_url($input) {
if (!strstri($input, 'http://')) {
return false;
}
return true;
}
?>
Simple example:
<?php
if (!validate_email($_POST['email'])) {
print 'You did not enter a valid email adress';
}
if (!validate_url($_POST['url'])) {
print 'You did not enter a valid url.';
}
?>


php dot net

Use this function to return the number of files matching a certain type (extention) in a given folder:
Using the previous code in the function above, file extentions like .ext.inc.php will be counted as .php files
usage:
returns false if dir doesnt exist
or returns the number of files counted
DO NOT add '.' to extention you are searching for.
example usage:
$result = CountFiles("./images", "jpg");
if($result === false) die("dir does not exist!");
function CountFiles($dir, $type)
{
if(!($dh =@opendir("$dir")))
 return false; // directory does not exist
 
// read the directory contents searching for "type" files
// and count how many are found:
 $files = 0;
 while ( ! ( ($fn = readdir($dh)) === false ) )
   {
   $f = strrev($fn);
   $ext = substr($f, 0, strpos($f,"."));
   $f_ext = strrev($ext);
if(( strcasecmp($f_ext, $type) == 0 )) $files++;
   }
 closedir($dh);
 return $files;
}


sam_at_compasspointmedia.com

This function is tricky! The problem lies when the haystack is a string and the needle is a number.  I found out the hard way:
This expression:
echo $spy = stristr("James Bond 007","007");
will return "007":
but this will not:
echo $spy = stristr("James Bond 007",007);
because 007 is interpreted as a number.  Tricky, right?
Even if the first parameter could be interpreted as a number, but the second parameter is in quotes, it won't work.  For example:
echo stristr("555007",007);
will not return anything.
but this will by the way...
echo $spy = stristr(555007,"007");


dpatton.at.confluence.org

There was a change in PHP 4.2.3 that can cause a warning message
to be generated when using stristr(), even though no message was
generated in older versions of PHP.
The following will generate a warning message in 4.0.6 and 4.2.3:
 stristr("haystack", "");
    OR
 $needle = "";  stristr("haystack", $needle);
This will _not_ generate an "Empty Delimiter" warning message in
4.0.6, but _will_ in 4.2.3:
 unset($needle); stristr("haystack", $needle);
Here's a URL that documents what was changed:
http://groups.google.ca/groups?selm=cvshholzgra1031224321%40cvsserver


spam

Regarding triadsebas at triads dot buildtolearn dot net entry for validating emails, etc.
To use these functions, you need to replace strstri() with stristr() as strstri does not exist.


paulphp

Regarding the problem (posted by Dan) of checking for a zero where the zero is at the end of a string, the following will work.  Note that !== is used rather than != which doesn't work.
$total = "Your total is 0";
$srchstrng = "0";
if (stristr($total, $srchstrng) !== FALSE)
   {
   echo "you have nothing";    
   }
This will correctly output "you have nothing", indicating the zero was correctly identified as being in the $total string.
(Discovered after experimenting with comparison operators detailed on this page: http://www.php.net/manual/en/language.operators.comparison  .)


trojjer

Regarding previous entry about validation:
"Note:  If you only want to determine if a particular needle  occurs within haystack, use the faster and less memory intensive function strpos() instead."
You have to use strpos('haystack','needle')!==false though, of course, incase it returns zero as the actual position, like it says on that page.


giz

Just been caught out by stristr trying to converting the needle from an Int to an ASCII value.
Got round this by casting the value to a string.
if( !stristr( $file, (string) $myCustomer->getCustomerID()  ) ) {
// Permission denied
}


art

handy little bit of code I wrote to take arguments from the command line and parse them for use in my apps.
<?php
$i = implode(" ",$argv); //implode all the settings sent via clie
$e = explode("-",$i); // no lets explode it using our defined seperator '-'
      //now lets parse the array and return the parameter name and its setting
      // since the input is being sent by the user via the command line
      //we will use stristr since we don't care about case sensitivity and
      //will convert them as needed later.
   while (list($index,$value) = each($e)){
      //lets grap the parameter name first using a double reverse string
      // to get the begining of the string in the array then reverse it again
      // to set it back. we will also "trim" off the "=" sign
    $param = rtrim(strrev(stristr(strrev($value),'=')),"=");
      //now lets get what the parameter is set to.
      // again "trimming" off the = sign
    $setting = ltrim(stristr($value,'='),"=");
      // now do something with our results.
      // let's just echo them out so we can see that everything is working
     echo "Array index is ".$index." and value is ".$value."\r\n";
     echo "Parameter is ".$param." and is set to ".$setting."\r\n\r\n";
}
?>
when run from the CLI this script returns the following.
[root@fedora4 ~]# php a.php -val1=one -val2=two -val3=three
Array index is 0 and value is a.php
Parameter is  and is set to
Array index is 1 and value is val1=one
Parameter is val1 and is set to one
Array index is 2 and value is val2=two
Parameter is val2 and is set to two
Array index is 3 and value is val3=three
Parameter is val3 and is set to three
[root@fedora4 ~]#


stoyan

Be careful never to use integer value as a needle - always convert it to string before use e.g. using strval() - otherwise you'll get messed up - for example te following:
if ($res=stristr('40', 52)) echo $res;
will return '40' as $res - simply 52 is the ASCII code of '4' that's in the beginning of our string.
Actually that's covered in the description of the function but you may miss to pay attention to it just like me=]


techdeck

An example for the stristr() function:
<?php
$a = "I like php";
if (stristr("$a", "LikE PhP")) {
print ("According to \$a, you like PHP.");
}
?>
It will look in $a for "like php" (NOT case sensetive. though, strstr() is case-sensetive).
For the ones of you who uses linux.. It is similiar to the "grep" command.
Actually.. "grep -i".


moenm@hotmail_com

A slightly more efficient way of getting a files extension. There is no reason to use strrev().
function getext($f) {
$ext = substr($f, strrpos($f,".") + 1);
return $ext;
}


notepad

<?php
function stristr_reverse($haystack, $needle) {
 $pos = stripos($haystack, $needle) + strlen($needle);
 return substr($haystack, 0, $pos);
}
$email = 'USER@EXAMPLE.com';
echo stristr_reverse($email, 'er');
// outputs USER
?>


Change Language


Follow Navioo On Twitter
addcslashes
addslashes
bin2hex
chop
chr
chunk_split
convert_cyr_string
convert_uudecode
convert_uuencode
count_chars
crc32
crypt
echo
explode
fprintf
get_html_translation_table
hebrev
hebrevc
html_entity_decode
htmlentities
htmlspecialchars_decode
htmlspecialchars
implode
join
levenshtein
localeconv
ltrim
md5_file
md5
metaphone
money_format
nl_langinfo
nl2br
number_format
ord
parse_str
print
printf
quoted_printable_decode
quotemeta
rtrim
setlocale
sha1_file
sha1
similar_text
soundex
sprintf
sscanf
str_getcsv
str_ireplace
str_pad
str_repeat
str_replace
str_rot13
str_shuffle
str_split
str_word_count
strcasecmp
strchr
strcmp
strcoll
strcspn
strip_tags
stripcslashes
stripos
stripslashes
stristr
strlen
strnatcasecmp
strnatcmp
strncasecmp
strncmp
strpbrk
strpos
strrchr
strrev
strripos
strrpos
strspn
strstr
strtok
strtolower
strtoupper
strtr
substr_compare
substr_count
substr_replace
substr
trim
ucfirst
ucwords
vfprintf
vprintf
vsprintf
wordwrap
eXTReMe Tracker