strstr

(PHP 4, PHP 5, PHP 7)

strstr문자열이 처음으로 나오는 부분을 찾습니다

설명

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

needle에서 haystack이 처음 발견된 곳부터 끝까지의 부분 문자열을 반환합니다.

Note:

이 함수는 대소문자를 구분합니다. 구분하지 않으려면, stristr()을 사용하십시오.

Note:

haystack 안에 needle이 있는지만 확인하려면, 빠르고 메모리도 적게 사용하는 strpos()를 사용하십시오.

인수

haystack

입력 문자열.

needle

needle이 문자열이 아니면, 정수로 변환하여 해당하는 값의 문자를 적용합니다.

before_needle

TRUE이면 (기본값은 FALSE) haystack에서 첫 needle의 앞에 있는 부분을 반환합니다.

반환값

문자열의 부분을 반환하거나, needle을 발견하지 못하면 FALSE를 반환합니다.

변경점

버전 설명
5.3.0 선택적인 before_needle 인수 추가.
4.3.0 strstr()이 바이너리 안전하게 되었습니다.

예제

Example #1 strstr() 예제

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

$user strstr($email'@' true); // PHP 5.3.0부터
echo $user// name 출력
?>

참고

  • preg_match() - 정규표현식 매치를 수행
  • stristr() - 대소문자를 구분하지 않는 strstr
  • strpos() - 문자열이 처음 나타나는 위치를 찾습니다
  • strrchr() - 문자열에서 문자가 마지막으로 나오는 부분을 찾습니다
  • substr() - Return part of a string

add a note add a note

User Contributed Notes 9 notes

up
34
laszlo dot heredy at gmail dot com
10 years 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
21
gruessle at gmail dot com
13 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
9
xslidian at lidian dot info
11 years 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
8
w3b_monk3y at yahoo dot com
15 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
10
brett dot jr dot alton at gmail dot com
16 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
0
trent dot renshaw at objectst dot com dot au
8 years ago
> 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);
up
-1
Gevorg Melkumyan
3 years ago
Don't  confuse this function with strtr ) I lost like 1 hour on that
up
-19
root at mantoru dot de
16 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
-25
leo dot nard at free dot fr
18 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;
}
?>
To Top