Current Location: Home> Function Categories> strstr

strstr

Find the first occurrence of a string
Name:strstr
Category:String
Programming Language:php
One-line Description:Find the specified substring in the string and return the part from the beginning of the substring to the end of the string

Function name: strstr()

Applicable version: PHP 4, PHP 5, PHP 7

Function description: The strstr() function is used to find the specified substring in a string and return the part from the substring to the end of the string. If no substring is found, false is returned.

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

parameter:

  • haystack: The string in which to look for the substring.
  • needle: The substring to be found. Can be a string or an array.
  • before_needle (optional): If set to true, the part before the needle is returned; if set to false (default), the part after the needle is returned.

Return value:

  • If a substring is found, return the part from the substring to the end of the string.
  • If no substring is found, false is returned.

Example:

 // 示例1:查找子字符串,并返回从子字符串开始到字符串结尾的部分$haystack = "Hello, world!"; $needle = "world"; $result = strstr($haystack, $needle); echo $result; // 输出:world! // 示例2:查找子字符串,并返回子字符串之前的部分$haystack = "Hello, world!"; $needle = ","; $result = strstr($haystack, $needle, true); echo $result; // 输出:Hello // 示例3:未找到子字符串,返回false $haystack = "Hello, world!"; $needle = "foo"; $result = strstr($haystack, $needle); var_dump($result); // 输出:bool(false)

Notes:

  • This function is case sensitive. If you need to do case-insensitive searches, you can use the strrist() function.
  • If the needle is an array, the function will look up each element and return the first found substring and its subsequent parts.
  • Starting with PHP 8.0, the before_needle parameter will no longer be supported. If you need to return the part before the substring, you can use the substr() function to implement it.
Similar Functions
Popular Articles