Core Function StrChr

From Sputnik Wiki
Jump to: navigation, search
StrChr( <haystack>, <char>, <start>, <count> )

Contents

Description

Locate first occurrence of character in string.

Returns the position to the first occurrence of character in the string.

The terminating null-character is considered part of the string. Therefore, it can also be located in order to retrieve the length of the string.

Parameters

haystack

The string to search in.

char

Character to be located.

start

Optional; Start position to begin searching the haystack from.

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

Default: 0

count

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

If count 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

The position to the first occurrence of character in the haystack.

If the character is not found, the function returns a null.

Remarks

None.

Example

$str = "This is a sample string";
printf ("Looking for the 's' character in \"%s\"...\n",$str);
$pch = strchr($str, 's');
while ($pch !== NULL)
{
	printf ("found at %d\n", $pch);
	$pch = strchr($str, 's', $pch + 1);
}
return 0;
// Prints
// Looking for the 's' character in "This is a sample string"...
// found at 3
// found at 6
// found at 10
// found at 17

Example of returning the rest of the string after a match

$str = "This is a sample; string";
printf ("Looking for the ';' character in \"%s\"...\n",$str);
$pch = strchr($str, ';');
printf ("found at %d\n", $pch);
printf ("Rest of string from '%d' is '%s'\n", $pch, substr($str, $pch));
// Prints
// Looking for the ';' character in "This is a sample; string"...
// found at 16
// Rest of string from '16' is '; string'

Example of using start parameter

$str = "This is; a sample; string";
printf ("Looking for the ';' character in \"%s\"...\n",$str);
$pch = strchr($str, ';', 8);
printf ("found at %d\n", $pch);
printf ("Rest of string from '%d' is '%s'\n", $pch, substr($str, $pch));
// Prints
// Looking for the ';' character in "This is; a sample; string"...
// found at 17
// Rest of string from '17' is '; string'

Example of using negative start parameter

$str = "This is; a sample; str;ing";
printf ("Looking for the ';' character in \"%s\"...\n",$str);
$pch = strchr($str, ';', -4);
printf ("found at %d\n", $pch);
printf ("Rest of string from '%d' is '%s'\n", $pch, substr($str, $pch));
// Prints
// Looking for the ';' character in "This is; a sample; str;ing"...
// found at 22
// Rest of string from '22' is ';ing'
Personal tools
Namespaces
Variants
Actions
Navigation
Toolbox