PHP 5.4.33 Released

strstr

(PHP 4, PHP 5)

strstrFindet das erste Vorkommen eines Strings

Beschreibung

string strstr ( string $haystack , mixed $needle [, bool $before_needle = false ] )

Gibt den Teil der Zeichenkette haystack ab dem ersten Vorkommen von needle bis zum Ende von haystack zurück.

Hinweis:

Diese Funktion unterscheidet zwischen Groß- und Kleinschreibung. Soll die Suche nicht zwischen Groß- und Kleinschreibung unterscheiden, verwenden Sie stristr().

Hinweis:

Wenn Sie nur herausfinden möchten, ob ein bestimmter needle innerhalb von haystack vorkommt, verwenden Sie stattdessen die schnellere und weniger speicherintensive Funktion strpos().

Parameter-Liste

haystack

Die Eingabezeichenkette.

needle

Ist needle kein String, wird der Parameter in einen Integerwert konvertiert, der dem Ordinalwert des Zeichens entspricht.

before_needle

Ist der Wert auf TRUE gesetzt, gibt strstr() den Teil von haystack zurück, der sich vor dem ersten Vorkommen von needle befindet.

Rückgabewerte

Gibt einen Teil der Zeichenkette zurück. Wird needle nicht gefunden, wird FALSE zurückgegeben.

Changelog

Version Beschreibung
5.3.0 Der optionale Parameter before_needle wurde hinzugefügt.
4.3.0 strstr() ist nun binary safe.

Beispiele

Beispiel #1 strstr()-Beispiel

<?php
$email  
'name@example.com';
$domain strstr($email'@');
echo 
$domain// Ausgabe: @example.com

$user strstr($email'@'true); // Ab PHP 5.3.0
echo $user// Ausgabe: name
?>

Siehe auch

  • preg_match() - Führt eine Suche mit einem regulären Ausdruck durch
  • stristr() - Wie strstr, aber unabhängig von Groß- bzw. Kleinschreibung
  • strpos() - Sucht das erste Vorkommen des Suchstrings
  • strrchr() - Sucht das letzte Vorkommen eines Zeichens in einem String
  • substr() - Gibt einen Teil eines Strings zurück

add a note add a note

User Contributed Notes 11 notes

up
11
brett dot jr dot alton at gmail dot com
6 years ago
For the needle_before (first occurance) parameter when using PHP 5.x or less, try:

<?php
$haystack
= 'php-homepage-20071125.png';
$needle = '-';
$result = substr($haystack, 0, strpos($haystack, $needle)); // $result = php
?>
up
11
gruessle at gmail dot com
3 years ago
Been using this for years:

<?php
/**
*
* @author : Dennis T Kaplan
*
* @version : 1.0
* Date : June 17, 2007
* Function : reverse strstr()
* Purpose : Returns part of haystack string from start to the first occurrence of needle
* $haystack = 'this/that/whatever';
* $result = rstrstr($haystack, '/')
* $result == this
*
* @access public
* @param string $haystack, string $needle
* @return string
**/

function rstrstr($haystack,$needle)
    {
        return
substr($haystack, 0,strpos($haystack, $needle));
    }
?>

You could change it to:
rstrstr ( string $haystack , mixed $needle [, int $start] )
<?php

function rstrstr($haystack,$needle, $start=0)
    {
        return
substr($haystack, $start,strpos($haystack, $needle));
    }

?>
up
8
laszlo dot heredy at gmail dot com
10 months ago
strstr() is not a way to avoid type-checking with strpos().

If $needle is the last character in $haystack, and testing $needle as a boolean by itself would evaluate to false, then testing strstr() as a boolean will evaluate to false (because, if successful, strstr() returns the first occurrence of $needle along with the rest of $haystack).

<?php
findZero
('01234');  // found a zero
findZero('43210');  // did not find a zero
findZero('0');      // did not find a zero
findZero('00');     // found a zero
findZero('000');    // found a zero
findZero('10');     // did not find a zero
findZero('100');    // found a zero

function findZero($numberString) {
    if (
strstr($numberString, '0')) {
        echo
'found a zero';
    } else {
        echo
'did not find a zero';
    }
}
?>

Also, strstr() is far more memory-intensive than strpos(), especially with longer strings as your $haystack, so if you are not interested in the substring that strstr() returns, you shouldn't be using it anyway.

There is no PHP function just to check only _if_ $needle occurs in $haystack; strpos() tells you if it _doesn't_ by returning false, but, if it does occur, it tells you _where_ it occurs as an integer, which is 0 (zero) if $needle is the first part of $haystack, which is why testing if (strpos($needle, $haystack)===false) is the only way to know for sure if $needle is not part of $haystack.

My advice is to start loving type checking immediately, and to familiarize yourself with the return value of the functions you are using.

Cheers.
up
4
w3b_monk3y at yahoo dot com
5 years ago
If you want to emulate strstr's new before_needle parameter pre 5.3 strtok is faster than using strpos to find the needle and cutting with substr. The amount of difference varies with string size but strtok is always faster.
up
1
gigaman2003 at halfempty dot co dot uk
7 years ago
Often you will need to find all occurrences of a string (for security escapes and such)

So I wrote this function to return an array with the locations of all the occurrences. Almost like an advanced strstr.

<?php
function findall($needle, $haystack)
{
   
//Setting up
   
$buffer=''; //We will use a 'frameshift' buffer for this search
   
$pos=0; //Pointer
   
$end = strlen($haystack); //The end of the string
   
$getchar=''; //The next character in the string
   
$needlelen=strlen($needle); //The length of the needle to find (speeds up searching)
   
$found = array(); //The array we will store results in
   
   
while($pos<$end)//Scan file
   
{
       
$getchar = substr($haystack,$pos,1); //Grab next character from pointer
       
if($getchar!="\n" || buffer<$needlelen) //If we fetched a line break, or the buffer is still smaller than the needle, ignore and grab next character
       
{
           
$buffer = $buffer . $getchar; //Build frameshift buffer
           
if(strlen($buffer)>$needlelen) //If the buffer is longer than the needle
           
{
               
$buffer = substr($buffer,-$needlelen);//Truncunate backwards to needle length (backwards so that the frame 'moves')
           
}
            if(
$buffer==$needle) //If the buffer matches the needle
           
{
               
$found[]=$pos-$needlelen+1; //Add the location of the needle to the array. Adding one fixes the offset.
           
}
        }
       
$pos++; //Increment the pointer
   
}
    if(
array_key_exists(0,$found)) //Check for an empty array
   
{
        return
$found; //Return the array of located positions
   
}
    else
    {
        return
false; //Or if no instances were found return false
   
}
}
?>

Haven't had the chance to speed test it, but many optimizations should be possible. It just works enough for me. Hope it saves someone a lot of time.
up
0
peter at olds dot co
2 years ago
I was in need of getting the first and last part of a string pre 5.3 so I wrote this:

<?php
$fir
= $first = explode( " ", $cmd[1] );
unset(
$fir[0] );
$end = ltrim( implode( " ", $fir ) );
?>

I needed it split with a " " but can obviously change for your needs. But with this format your output for the string:

"PHP is the best programming language out there"

Will give you the following results:

<?php
$first
[0] // PHP
$end // is the best programming language out there
?>

Works really well :)
up
-1
xslidian at lidian dot info
1 year ago
For those in need of the last occurrence of a string:

<?php
function strrstr($h, $n, $before = false) {
   
$rpos = strrpos($h, $n);
    if(
$rpos === false) return false;
    if(
$before == false) return substr($h, $rpos);
    else return
substr($h, 0, $rpos);
}
?>
up
-1
leo dot nard at free dot fr
9 years ago
When encoding ASCII strings to HTML size-limited strings, sometimes some HTML special chars were cut.

For example, when encoding "��" to a string of size 10, you would get: "à&a" => the second character is cut.

This function will remove any unterminated HTML special characters from the string...

<?php
function cut_html($string)
{
   
$a=$string;

    while (
$a = strstr($a, '&'))
    {
        echo
"'".$a."'\n";
       
$b=strstr($a, ';');
        if (!
$b)
        {
            echo
"couper...\n";
           
$nb=strlen($a);
            return
substr($string, 0, strlen($string)-$nb);
        }
       
$a=substr($a,1,strlen($a)-1);
    }
    return
$string;
}
?>
up
-2
php at silisoftware dot com
11 years ago
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:

<?php
$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:

<?php
$string
= strstr("one#two\x00three", "\x00");
// PHP 4.2.x:  $string contains ""
// PHP 4.3.0:  $string contains "\x00three"
?>
up
-3
root at mantoru dot de
6 years ago
Please note that $needle is included in the return string, as shown in the example above. This ist not always desired behavior, _especially_ in the mentioned example. Use this if you want everything AFTER $needle.

<?php
function strstr_after($haystack, $needle, $case_insensitive = false) {
   
$strpos = ($case_insensitive) ? 'stripos' : 'strpos';
   
$pos = $strpos($haystack, $needle);
    if (
is_int($pos)) {
        return
substr($haystack, $pos + strlen($needle));
    }
   
// Most likely false or null
   
return $pos;
}

// Example
$email = 'name@example.com';
$domain = strstr_after($email, '@');
echo
$domain; // prints example.com
?>
up
-6
prafe at prafesplace dot com
6 years ago
If you want to use the $before_needle parameter that's only in PHP 5.3.0, I found a way to use it in lower versions.

The code is a bit hefty, but it works. It also has added $include_needle and $case_sensitive.

<?php
// ==== I don't guarantee this is faster than the PHP 6 before needle, ====
// ====  but it works for PHP below 6 atleast. ====
// ==== IT ALSO HAS INCLUDE NEEDLE BOOLEAN.. ====
function strstrbi($haystack,$needle,$before_needle,
$include_needle,$case_sensitive)
{
 
$strstr = ($case_sensitive) ? 'strstr' : 'stristr';
  if(
$before_needle!=true && $before_needle!=false && isset($before_needle)){
      die(
'PHP: Error in function '.chr(39).'$strstrbi'. chr(39).' :  parameter '. chr(39).'$before_needle'.chr(39).' is not a supplied as a boolean.');
  }
// END BOOLEAN CHECK '$before_needle'

 
if($include_needle!=true && $include_needle!=false && isset($include_needle)){
    die(
'PHP: Error in function '.chr(39).'$strstrbi'. chr(39).' : parameter '. chr(39).'$include_needle'.chr(39). ' is not a supplied as a boolean.');
  }
// END BOOLEAN CHECK '$include_needle'

 
if($case_sensitive!=true && $case_sensitive!=false && isset($case_sensitive)){
    die(
'PHP: Error in function '.chr(39).'$strstrbi' .chr(39).' : parameter '. chr(39).'$case_sensitive'.chr(39).' is not a supplied as a boolean.');
  }
// END BOOLEAN CHECK '$case_sensitive'

 
if(!isset($before_needle)){
   
$before_needle=false;
  }

  if(!isset(
$include_needle)){
   
$include_needle=true;
  }

  if(!isset(
$case_sensitive)){
   
$case_sensitive=false;
  }

  switch(
$before_needle){
    case
true:
      switch(
$include_needle){
        case
true:
         
$temp=strrev($haystack);
         
$ret=strrev(substr($strstr($temp,$needle),0));
          break;
       
// END case true : $include_needle
       
case false:
         
$temp=strrev($haystack);
         
$ret=strrev(substr($strstr($temp,$needle),1));
          break;
       
// END case false : $include_needle
     
}
      break;
   
// END case true : $before_needle
   
case false:
      switch(
$include_needle){
        case
true:
         
$ret=$strstr($haystack,$needle);
          break;
       
// END case true: $include_needle
       
case false:
         
$ret=substr($strstr($haystack,$needle),1);
          break;
       
// END case false: $include_needle
   
}
    break;
   
// END case false : $before_needle
 
}

  if(!empty(
$ret)){
    return
$ret;
  }else{
    return
false;
  }
}
// === END FUNCTION 'strstrbi'

// Example

$email  = 'user@example.com';
$domain = strstrbi($email, '@', false, false, false);
echo
$domain; // prints example.com

$user = strstrbi($email, '@', true, false, false);
echo
$user; // prints user
?>
To Top