search for in the  
<strspnstrtok>
Last updated: Thu, 19 May 2005

strstr

(PHP 3, PHP 4, PHP 5)

strstr -- Find first occurrence of a string

Description

string strstr ( string haystack, string needle )

Returns part of haystack string from the first occurrence of needle to the end of haystack.

If needle is not found, returns FALSE.

If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.

Note: This function is case-sensitive. For case-insensitive searches, use stristr().

Example 1. strstr() example

<?php
$email
= 'user@example.com';
$domain = strstr($email, '@');
echo
$domain; // prints @example.com
?>

Note: If you only want to determine if a particular needle occurs within haystack, use the faster and less memory intensive function strpos() instead.

strstr() has been binary safe since PHP 4.3.0

See also ereg(), preg_match(), stristr(), strpos(), strrchr(), and substr().



User Contributed Notes
strstr
rodrigo at fabricadeideias dot com
22-Apr-2005 02:55
A better solution for nicolas at bougues dot net's problem below is to use

<?
strstr
("0", "0") === FALSE
?>

instead of

<?
strstr
("0", "0") == FALSE
?>

or

<?
is_string
(strstr ("0", "0"))
?>
22-Apr-2005 08:45
Regarding the note left by nicolas at bougues dot net on 26-Sep-2002 11:53, where he stated

> The following expression
>
> strstr ("0", "0") == FALSE
>
> is TRUE, which is obviously not what one's want when comparing to FALSE.
>
> If you just want to know iff haystack contains needle, without such ambiguity, use is_string (strstr ("0", "0")), which will evaluate to TRUE.

Use the === operator instead. Thus,

str ("0", "0") === FALSE

if FALSE as expected.
mikkel at hansen dot net
15-Apr-2005 08:04
With regard to robbie and the post at "04-Mar-2005 04:52": if a filename contains more than one full stop, the two scripts below will fail in finding to correct file extension.

The following code handles filenames like "document.about.ducks.doc" correctly.

function findtype($file) {
   $revfile = strrev($file);
   $type = strtolower( strrev(substr($revfile,0,strpos($revfile,"."))) );

   return $type;
}
robbie [at] averill [dot] co [dot] nz
18-Mar-2005 07:07
With regard to the below comment

<?php
$filename
= "funnypicture.jpg";
$type = str_replace('.','',strstr($filename, '.'));
echo
$type; // jpg
?>

This gets the file extension into the variable $type, not the file type.

To get the file type, use filetype(), or to get the MIME content type, use mime_content_type().

<?php
$filename
= "funnypicture.jpg";
$ext = str_replace('.','',strstr($filename, '.'));
$type = filetype($filename);
$mime = mime_content_type($filename);
echo
$ext;    // jpg
echo $type// file
echo $mime; //  image/jpeg
?>
04-Mar-2005 09:52
Getting file extension -

<?php
$filename
= "funnypicture.jpg";
$type = str_replace('.','',strstr($filename, '.'));
echo
$type; // jpg
?>
redzia
08-Feb-2005 09:54
Example usage of fopen to remove line containing a key string
<?

$key
= "w3ty8l";

//load file into $fc array

$fc=file("some.txt");

//open same file and use "w" to clear file

$f=fopen("some.txt","w");

//loop through array using foreach

foreach($fc as $line)
{
     if (!
strstr($line,$key)) //look for $key in each line
          
fputs($f,$line); //place $line back in file
}
fclose($f);

?>
steve at alittlefinesse dot com
03-Sep-2004 10:55
// I needed to find the content between 2 chrs in a string and this was the quickest method I could find.

function SeekVal($str_in) {

$tween="";  // not needed but good practise when appending
$chr1='[';
$chr2=']';

for ($i=strpos($str_in, $chr1);$i<strpos($str_in, $chr2);$i++)
  $tween=$tween+$str_in[$i];

return $tween;   
}
Ami Hughes (ami at mistress dot name)
22-Apr-2004 11:02
Because I was working with two different sets of variables and wanted to combine the result into a decimal format, I needed to strip the zero before the decimal.  As an added bonus, this will strip anything before a decimal (or period), which might be useful for other things.  So, if you are trying to combine apples and oranges like I was, or whatever, try this.  =)

<?php
$number
= '0.529';
strstr($number,'.');
echo
$number; // returns .529
?>
schultz at widescreen dot ch
01-Apr-2004 04:22
a nice way to decide wether a string starts with a certain prefix, one can use this condition...

$url = 'http://www.widescreen.ch';
$isUrl = ( strstr($url,'http://') == $url );

have  fun!
Lars
giunta dot gaetano at sea-aeroportimilano dot it
23-Feb-2004 08:16
Note to Rolf's post: if the needle is NOT found, the function proposed will truncate the last char of the string!
Romuald Brunet
21-Jan-2004 02:25
Regarding the note of the manual concerning the speed of strstr against strpos, for people who wants to check a needle occurs within haystack, it apprears that strstr() is in facts faster than strpos().

Example:
<?php
// [VERY] Quick email check:
if ( strstr("email@domain.tld", "@") ) {
// Ok
}
?>

is faster than

<?php
if ( strpos("email@domain.tld", "@") !== FALSE ) {
// Ok
}

Without using the true equality with !==, strpos() is faster. But then if the haystack starts with needle the condition whould not be met.
teezee
14-Mar-2003 05:08
//Checking and using the above string can be done much easier:

$data="ID: 1, Rolf Winterscheidt, and so on";
$data_array = explode(",",$data);

//will return an array:
 $data[0] = ID: 1
 $data[1] =  Rolf Winterscheidt
 $data[2] =  and so on
rolf dot winterscheidt at rowitech dot de
07-Mar-2003 06:02
Get the first part of the string can be so easy:

$data="ID: 1, Rolf Winterscheidt, and so on";
$id=substr($data, 0 , strpos($data, ",")-1);
-> $id is now "ID: 1"

Best regards,
Rolf
crypto at notup2u dot net
01-Mar-2003 07:44
I've noticed that :

$string = substr($string, 0, strpos($string,$separat));

returns the first par of the string (before $separat) only if there is $separat in the string !

But

$string = substr($string, 0, strlen($string)-strlen (strstr ($string,$separat)));

works anyway ...

That can be useful !

/Crypto
php at silisoftware dot com
14-Feb-2003 05:37
PHP versions before 4.3.0 (tested on 4.2.2 and 4.2.3) return the $haystack from $needle only up to the first null character. So for example:

$string = strstr("one#two\x00three", "#");
// PHP 4.2.x:  $string contains "#two"
// PHP 4.3.0:  $string contains "#two\x00three"

If you're trying to match nulls, you will probably get back an empty string:

$string = strstr("one#two\x00three", "\x00");
// PHP 4.2.x:  $string contains ""
// PHP 4.3.0:  $string contains "\x00three"
joaobett at oninet dot pt
22-Jan-2003 10:07
[Editor's Note: It's better to:

  substr($stringA, 0, strpos($stringA, $toFind)+1)

than to reverse the string twice (slow).]

//If you want to get the text before the occurence of the character
//you want to find, simply use the function strRev twice:

$stringA = "user@example.com";    $toFind = "@";

echo strrev( strchr(strrev($stringA),$toFind) );

//output: user@
mario at comicide dot com
30-Dec-2002 12:58
If you would like to count files on a directory, this might be helpful.  In this case I wanted to create a random image generator, but not have to keep track of the image count. Example: I have 4 images, and choose a random number between 1-4.  If I decide to add a 5th and 6th image, I would have to generate at random 1-6. STRSTR can help you keep track of the amount of images, without you having to update the code.

NOTE, this example is based on the naming convention

image1.gif
image2.gif
image3.gif
""""""""4"""
etc....

If you are not using it, then just make the adjustments.
------------------------------------------------------
//First a function. $path is where you want to count files
//$filter is the criteria. Ex. File names with "image" in it.

function countfiles($path, $filter)
{

$dir = opendir($path);

while ($file = readdir($dir)){

     if(strstr($file, $filter)){ $i++; }
}//end while

closedir($dir);

return $i;

}
//-------------------------------------------------

$max = countfiles("/you directory", "image");
$num = rand(1,$max);
$image = "image";
$image.= $num;
$image.= ".gif";  // or jpg, png, etc

echo "<img scr=\"$image\">";
nin at screamingslaves dot com
28-Dec-2002 02:54
Since I managed to do this in a few seconds, why not let it out to someone in the same need ...

Based on the above idea, since I had:

$string = "Some text (some note) some other text";

And say you just wanted whats *between* the parentheses (or between basically anything):

<?

function remover($string, $sep1, $sep2)
{
      
$string = substr($string, 0, strpos($string,$sep2));
      
$string = substr(strstr($string, $sep1), 1);

       return
$string;
}

$string = "Some text (some note) some other text";
$str1 = "(";
$str2 = ")";

echo
remover($string, $str1, $str2);

?>
fred at debilitron dot com
08-Nov-2002 07:44
The same thing as above, but a bit shorter, with strpos() :

$string = "email@domain.net";

$separat = "@";
$string = substr($string, 0, strpos($string,$separat));
john :: beech :: at :: mkv25 :: dot :: net
08-Nov-2002 07:42
function backstr($haystack, $needle) {
       return substr($haystack, 0, strlen($haystack) - strlen(strstr($haystack,$needle)));
}

An extension of the above code, the function backstr will do the same as strstr, but returns the string back from the needle instead of forward.

echo backstr("joanne@home.net", "@");    // Outputs 'Joanne'

Always try to make things easy for your self, and keep code uncluttered!
crypto at notup2u dot net
31-Oct-2002 09:33
Here is a small command to get the beginning of a string until another string. This is a bit like strstr() but it returns the beginning and not the end of the string !

Voici une petite commande pour obtenir le début d'une chaine de charactères jusqu'à une autre chaine. C'est un peu comme strstr() mais celà retourne le début et non la fin de la chaine !

$string = "email@domain.net";

$separat = "@";
$string = substr($string, 0, strlen($string)-strlen (strstr ($string,$separat)));

// $string : "email"

/Crypto
duke as mastre dot com
15-Oct-2002 12:11
strstr(), strchr(), strrchr() _and_ stristr() are _all_ broken as of 4.2.3:

$haystack = 'John Doe <john@doe.com>';
$needle_broken = '<';
$needle_ok = '@';

echo('haystack: ' . htmlspecialchars($haystack) . '<br />');
echo('strstr using needle_broken: ' . strstr($haystack, $needle_broken) . '<br />');
echo('strstr using needle_ok: ' . strstr($haystack, $needle_ok) . '<br />');

output:
broken:
ok: @doe.com>

only function that works properly with this caracter (also '>' and possibly others) is strpos()
nicolas at bougues dot net
26-Sep-2002 12:53
The following expression

strstr ("0", "0") == FALSE

is TRUE, which is obviously not what one's want when comparing to FALSE.

If you just want to know iff haystack contains needle, without such ambiguity, use is_string (strstr ("0", "0")), which will evaluate to TRUE.
arni at linux dot is
23-Nov-2000 12:00
This functions is also widely used for checking if a string is in a string since it returns false if the string was not found in container.

$string = "PHP";
$container = "I love writing PHP code.";

if(strstr($container,$string)) {
     echo "found it.";
} else {
     echo "not found.";
}
wls at wwco dot com
01-Oct-2000 01:07
If you're looking for the index of where the string starts, see strpos()

<strspnstrtok>
 Last updated: Thu, 19 May 2005
Copyright © 2001-2005 The PHP Group
All rights reserved.
This unofficial mirror is operated at: The Server Pages
Last updated: Thu May 19 17:35:34 2005 CDT