strstr
Возвращает подстроку строки haystack , начиная с первого вхождения needle (и включая его) и до конца строки haystack .
Замечание:
Эта функция учитывает регистр символов. Для поиска без учёта регистра используйте stristr() .
Замечание:
Если нужно лишь определить, встречается ли подстрока needle в haystack , используйте более быструю и менее ресурсоёмкую функцию strpos() .
Список параметров
До PHP 8.0.0, если параметр needle не является строкой, он преобразуется в целое число и трактуется как код символа. Это поведение устарело с PHP 7.3.0, и полагаться на него крайне не рекомендуется. В зависимости от предполагаемого поведения, параметр needle должен быть либо явно приведён к строке, либо должен быть выполнен явный вызов chr() .
Если установлен в true , strstr() возвращает часть строки haystack до первого вхождения needle (исключая needle).
Возвращаемые значения
Возвращает часть строки или false , если needle не найдена.
Список изменений
Версия | Описание |
---|---|
8.0.0 | Передача целого числа ( int ) в needle больше не поддерживается. |
7.3.0 | Передача целого числа ( int ) в needle объявлена устаревшей. |
Примеры
Пример #1 Пример использования strstr()
$email = ‘name@example.com’ ;
$domain = strstr ( $email , ‘@’ );
echo $domain ; // выводит @example.com
?php
$user = strstr ( $email , ‘@’ , true );
echo $user ; // выводит name
?>
Смотрите также
- stristr() — Регистронезависимый вариант функции strstr
- strrchr() — Находит последнее вхождение символа в строке
- strpos() — Возвращает позицию первого вхождения подстроки
- strpbrk() — Ищет в строке любой символ из заданного набора
- preg_match() — Выполняет проверку на соответствие регулярному выражению
User Contributed Notes 10 notes
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).
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.
Been using this for years:
/**
*
* @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] )
function rstrstr ( $haystack , $needle , $start = 0 )
return substr ( $haystack , $start , strpos ( $haystack , $needle ));
>
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.
For those in need of the last occurrence of a string:
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 );
>
?>
For the needle_before (first occurance) parameter when using PHP 5.x or less, try:
$haystack = ‘php-homepage-20071125.png’ ;
$needle = ‘-‘ ;
$result = substr ( $haystack , 0 , strpos ( $haystack , $needle )); // $result = php
?>
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:
$result = $needle ? strstr ( $haystack , $needle ) : false ;
?>
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:
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.
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
?>
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.
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 ;
>
?>
stristr
Возвращает всю строку haystack начиная с первого вхождения needle включительно.
Список параметров
Строка, в которой производится поиск
До PHP 8.0.0, если параметр needle не является строкой, он преобразуется в целое число и трактуется как код символа. Это поведение устарело с PHP 7.3.0, и полагаться на него крайне не рекомендуется. В зависимости от предполагаемого поведения, параметр needle должен быть либо явно приведён к строке, либо должен быть выполнен явный вызов chr() .
Если установлен в true , stristr() возвращает часть строки haystack до первого вхождения needle (не включая needle).
needle и haystack обрабатываются без учёта регистра.
Возвращаемые значения
Возвращает указанную подстроку. Если подстрока needle не найдена, возвращается false .
Список изменений
Версия | Описание |
---|---|
8.2.0 | Преобразование регистра больше не зависит от локали, установленной с помощью функции setlocale() . Будут преобразованы только символы ASCII. Байты не ASCII-кодировке будут сравниваться по значению байта. |
8.0.0 | Передача целого числа ( int ) в needle больше не поддерживается. |
7.3.0 | Передача целого числа ( int ) в needle объявлена устаревшей. |
Примеры
Пример #1 Пример использования stristr()
$email = ‘USER@EXAMPLE.com’ ;
echo stristr ( $email , ‘e’ ); // выводит ER@EXAMPLE.com
echo stristr ( $email , ‘e’ , true ); // выводит US
?>?php
Пример #2 Проверка на вхождение строки
$string = ‘Hello World!’ ;
if( stristr ( $string , ‘earth’ ) === FALSE ) echo ‘»earth» не найдена в строке’ ;
>
// выводит: «earth» не найдена в строке
?>?php
Пример #3 Использование не строки в поиске
Примечания
Замечание: Эта функция безопасна для обработки данных в двоичной форме.
Смотрите также
- strstr() — Находит первое вхождение подстроки
- strrchr() — Находит последнее вхождение символа в строке
- stripos() — Возвращает позицию первого вхождения подстроки без учёта регистра
- strpbrk() — Ищет в строке любой символ из заданного набора
- preg_match() — Выполняет проверку на соответствие регулярному выражению
User Contributed Notes 8 notes
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);
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
>
?>
An example for the stristr() function:
$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».
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
I think there is a bug in php 5.3 in stristr with uppercase Ä containing other character
if you search only with täry it works, but as soon as the word is tärylä it does not. TÄRYL works fine
function aim ( $page ) if( stristr ( $_SERVER [ ‘REQUEST_URI’ ], $page )) return ‘ ‘ ;
>
>
?>
usage:
handy little bit of code I wrote to take arguments from the command line and parse them for use in my apps.
$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 » default»>$param = rtrim ( strrev ( stristr ( strrev ( $value ), ‘=’ )), » keyword»>);
//now lets get what the parameter is set to.
// again «trimming» off the = sign
$setting = ltrim ( stristr ( $value , ‘=’ ), » keyword»>);
// 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=threeArray 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