strstr

(PHP 4, PHP 5)

strstr — Находит первое вхождение подстроки

Описание

string strstr ( string $haystack , string $needle )

Возвращает подстроку строки haystack начиная с первого вхождения needle до конца строки.

Если подстрока needle не найдена, возвращает FALSE.

Если needle не является строкой, он приводится к целому и трактуется как код символа.

Замечание: Эта функция учитывает регистр символов. Для поиска без учета регистра используйте stristr().

Пример #1 Пример использования strstr()

<?php
$email 
'user@example.com';
$domain strstr($email'@');
echo 
$domain// выводит @example.com
?>

Замечание: Если нужно лишь определить, встречается ли подстрока needle в haystack , используйте функцию strpos(), которая работает быстрее и потребляет меньше памяти.

С версии PHP 4.3.0 strstr() безопасна для обработки данных в двоичной форме.

См. также описание функций ereg(), preg_match(), stristr(), strpos(), strrchr() и substr().

Коментарии

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($string0strlen($string)-$nb);
        }
       
$a=substr($a,1,strlen($a)-1);
    }
    return 
$string;
}
?>
2005-05-24 05:12:18
http://php5.kiev.ua/manual/ru/function.strstr.html
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
?>
2007-11-10 05:22:43
http://php5.kiev.ua/manual/ru/function.strstr.html
For the needle_before (first occurance) parameter when using PHP 5.x or less, try:

<?php
$haystack 
'php-homepage-20071125.png';
$needle '-';
$result substr($haystack0strpos($haystack$needle)); // $result = php
?>
2007-11-25 10:02:35
http://php5.kiev.ua/manual/ru/function.strstr.html
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.
2009-01-20 02:28:04
http://php5.kiev.ua/manual/ru/function.strstr.html
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($haystack0,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));
    }

?>
2011-04-20 16:39:51
http://php5.kiev.ua/manual/ru/function.strstr.html
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($h0$rpos);
}
?>
2013-02-21 09:37:48
http://php5.kiev.ua/manual/ru/function.strstr.html
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.
2013-11-07 23:39:20
http://php5.kiev.ua/manual/ru/function.strstr.html
> root at mantoru dot de

PHP makes this easy for you. When working with domain portion of email addresses, simply pass the return of strstr() to substr() and start at 1:

substr(strstr($haystack, '@'), 1);
2015-06-25 05:08:14
http://php5.kiev.ua/manual/ru/function.strstr.html
Автор:
Don't  confuse this function with strtr ) I lost like 1 hour on that
2021-02-03 17:17:42
http://php5.kiev.ua/manual/ru/function.strstr.html
Автор:
Lookout for logic inversion in old code!

In PHP 8, if the needle is an empty string, this function will return 0 (not false), implying the first character of the string matches the needle. Before PHP 8, it would return false when the needle is an empty string.

There other string functions that are affected by similar issues in PHP 8: strpos(), strrpos(), stripos(), strripos(), strchr(), strrchr(), stristr(), and this function, strstr()

If you are checking if the return value === false then you will be misled by this new behaviour. You also need to check if the needle was an empty string. Basically, something like this:

<?php
$result 
$needle strstr($haystack$needle) : false;
?>
2023-02-10 17:46:24
http://php5.kiev.ua/manual/ru/function.strstr.html

    Поддержать сайт на родительском проекте КГБ