Core Function StrChr

From Sputnik Wiki
Revision as of 21:41, 11 August 2014 by UberFoX (Talk | contribs)
Jump to: navigation, search
StrChr( <haystack>, <char>, <start> )

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.

Can be negative this will cause it to start from haystack length - abs(start) instead.

Default: 0

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