strstr

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

strstrFind the first occurrence of a string

Опис

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

Returns part of haystack string starting from and including the first occurrence of needle to the end of haystack.

Зауваження:

This function is case-sensitive. For case-insensitive searches, use stristr().

Зауваження:

If it is only required to determine if a particular needle occurs within haystack, the faster and less memory intensive str_contains() function should be used instead.

Параметри

haystack

The input string.

needle

The string to search for.

До версії PHP 8.0.0, якщо параметр needle не є рядком, він перетворюється на ціле число і розглядається як код символу. Ця поведінка є застарілою, починаючи з PHP 7.3.0. Вкрай не рекомендується на неї покладатися. Залежно від потрібної поведінки, параметр needle необхідно привести до рядкового типу або обробити функцією chr().

before_needle

If true, strstr() returns the part of the haystack before the first occurrence of the needle (excluding the needle).

Значення, що повертаються

Returns the portion of string, or false if needle is not found.

Журнал змін

Версія Опис
8.0.0 Тепер параметр needle може бути порожнім рядком.
8.0.0 Passing an int as needle is no longer supported.
7.3.0 Passing an int as needle has been deprecated.

Приклади

Приклад #1 strstr() example

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

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

Прогляньте також

  • stristr() - Case-insensitive strstr
  • strrchr() - Find the last occurrence of a character in a string
  • strpos() - Знаходить позицію першого входження підрядка в рядку
  • strpbrk() - Search a string for any of a set of characters
  • preg_match() - Perform a regular expression match