Core Function StrPos

From Sputnik Wiki
Jump to: navigation, search
StrPos( <haystack>, <needle>, <flags>, <start>, <length> )

Contents

Description

Find the position of the first/last occurrence of a substring in a string

Parameters

haystack

The string to search in.

needle

The string to search for.

flags

1 = Case insensitive search

2 = Find last match instead of first

(Can add flags together)

Default: 0 (Case sensitive)

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, -1 will be returned.

Return Value

Returns the position of where the needle exists relative to the beginning of the haystack (independent of offset). Also note that string positions start at 0, and not 1.

Return -1 on failure (such as did not find)

Remarks

None.

Example

Find First:

$RET = StrPos("The quick brown FoX", "foX", 1);
println( $RET ); // 16

Find Last:

// Flag 1 for case ignore case then flag 2 for find last instead of first
$RET = StrPos("FoX the quick brown FoX", "foX", 1 | 2);
println( $RET ); // 20

Using stat/length

// make variables
$str =  "The quick brown foxFoX";
$find = "foX";
// get the last fox
$RET = StrPos($str, $find, 1, -3);
println( $RET );
say substr($str, $RET, 3);
// get the first fox
$RET = StrPos($str, $find, 1);
println( $RET );
say substr($str, $RET, 3);
// PRINTS
// 19
// FoX
// 16
// fox
Personal tools
Namespaces
Variants
Actions
Navigation
Toolbox