PHP.mk документација

strstr

Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.

function.strstr.php PHP.net прокси Преводот се освежува
Оригинал на PHP.net
Патека function.strstr.php Локална патека за оваа страница.
Извор php.net/manual/en Оригиналниот HTML се реупотребува и локално се стилизира.
Режим Прокси + превод во позадина Кодовите, табелите и белешките остануваат читливи во истиот тек.
strstr

Референца за `function.strstr.php` со подобрена типографија и навигација.

function.strstr.php

strstr

(PHP 4, PHP 5, PHP 7, PHP 8)

strstrНајди го првото појавување на стринг

= NULL

strstr(string $haystack, string $needle, bool $before_needle = false): string|false

Враќа дел од haystack стринг почнувајќи од и вклучувајќи го првото појавување на needle до крајот на haystack.

Забелешка:

Оваа функција е чувствителна на големи и мали букви. За пребарување што не е чувствително на големи и мали букви, користете stristr().

Забелешка:

Ако е потребно само да се утврди дали одреден needle се појавува во haystack, побрзиот и помалку интензивен за меморија str_contains() треба да се користи наместо тоа.

Параметри

haystack

, и враќа стринг со првиот карактер од

needle

Низата за пребарување.

Пред PHP 8.0.0, ако needle не е низа, се претвора во цел број и се применува како редниот број на карактер. Ова однесување е застарено од PHP 7.3.0 и силно се обесхрабрува да се потпирате на него. Во зависност од наменетото однесување, needle треба експлицитно да се префрли на низа, или експлицитно повикување на chr() треба да се изврши.

before_needle

Враќа true, strstr() враќа дел од haystack почнувајќи од и вклучувајќи го првиот појавен од needle (исклучувајќи го needle).

Вратени вредности

Враќа дел од стринг, или false if needle не е пронајден.

Дневник на промени

Верзија = NULL
8.0.0 needle сега прифаќа празна низа.
8.0.0 Поминување на int as needle веќе не се поддржува.
7.3.0 Поминување на int as needle е укинат.

Примери

Пример #1 strstr() example

<?php
$email
= '[email protected]';
$domain = strstr($email, '@');
echo
$domain, PHP_EOL; // prints @example.com

$user = strstr($email, '@', true);
echo
$user, PHP_EOL; // prints name
?>

Види Исто така

  • stristr() - strstr што не прави разлика помеѓу големи и мали букви
  • strrchr() Ги наоѓа последните појави на еден знак во низа во друга
  • strpos() - Најди ја позицијата на првото појавување на подниза во низа
  • strpbrk() - Пребарај низа за било кој од сет на знаци
  • preg_match() - Изврши совпаѓање со регуларен израз

Белешки од корисници 6 белешки

linus at flowingcreativity dot net
12 години пред
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.
Јулијан Егелстаф
3 години пред
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;
?>
Гевoрг Мелкумјан
пред 5 години
Don't  confuse this function with strtr ) I lost like 1 hour on that
xslidian на lidian точка info
пред 13 години
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);
}
?>
gruessle на gmail точка com
пред 14 години
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));
    }

?>
brett точка jr точка alton на gmail точка com
пред 18 години
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
?>
Навигација

Прелистувај сродни теми и функции.

На оваа страница

Автоматски outline од активната документација.

Насловите ќе се појават тука по вчитување.

Попрегледно читање

Примерите, changelog табелите и user notes се визуелно издвоени за да не се губат во долгата содржина.

Брз совет Користи го outline-от Скокни директно на главните секции од активната страница.
Извор Оригиналниот линк останува достапен Кога ти треба целосен upstream context, отвори го PHP.net во нов tab.