Core Function StrStr

From Sputnik Wiki
Jump to: navigation, search
StrStr( <haystack>, <needle>, <before_needle>, <find_last>, <case>, <start>, <length> )

Contents

Description

Find the first/last occurrence of a string

Parameters

haystack

The input string.

needle

If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.

before_needle

If TRUE, StrStr() returns the part of the haystack before the first/last occurrence of the needle (excluding the needle).

Default: false

find_last

If TRUE, StrStr() will find the last occurrence of the needle instead of the first.

Default: false

case

If TRUE, StrStr() will ignore case and do the comparison case insensitively.

Default: false

start

Optional; The starting position of the search.

OR

If the start is a negative value the character position will work backwards from the length of the string.

Default: 0

length

Optional; The number of characters to search. By default the entire remainder of the string.

If length is given and is negative, then that many characters will be omitted from the end of string (after the start position has been calculated when a start is negative). If start denotes the position of this truncation or beyond, NULL will be returned.

Return Value

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

Remarks

None.

Example

// basic example
$email  = 'name@example.com';
$domain = strstr($email, '@');
echo "Value: $domain\n"; // prints @example.com
 
// using before param to return the text before rather than after the find
$user = strstr($email, '@', true);
echo "Value: $user\n"; // prints name
 
$string1="google.com";  
$newstring=strstr($string1,".");  
echo "Value: $newstring\n";  // Prints .COM
 
// using find last param to find the last substring instead of the first
$string2="google.com.uk";  
$newstring1=strstr($string2,".", false, true);  
echo "Value: $newstring1\n";  // Prints .COM
 
// using ignore case param
$string3  = 'cats AnD dogs';
$newstring2 = strstr($string3, 'and', false, false, true);
echo "Value: $newstring2\n"; // prints AnD dogs

Using the start/length

$email  = 'cat@example.co.uk';
$domain = strstr($email, '@', false, false, false, 0, -3);
echo "Value: $domain\n"; // prints @example.co
Personal tools
Namespaces
Variants
Actions
Navigation
Toolbox