Strings\firstPosition()

reducer returns Closure pure
(string, int, int) → (string → int | null)
At a glance — Bind a needle; the returned Closure yields the first offset, or null. Wraps strpos() / stripos().

Returns a function which can be used to find the first position of a defined sub string. The created function can then reused over any string, or used as part of a Higher Order Function such as array_filter().

/**
  * @param string $needle The value to look for.
  * @param int  $offset The offset to start
  * @param int $flags STRINGS_CASE_SENSITIVE | STRINGS_CASE_INSENSITIVE
  * @return Closure(string):?int
  */
Strings\firstPosition(string $needle, int $offset = 0, int $flags = STRINGS_CASE_SENSITIVE): Closure

Returned Closure

When Strings\firstPosition() is called, it returns the following Closure which can be used like a regular function.

/**
  * @param string $source
  * @return bool
  * @psalm-pure
  */ 
$function(string $source): bool

You can use the following constants to define the mode of the function:

Examples

Partial Application

This can be used to create a simple closure which can be used as a regular function.

// Create function to find the first position of 'foo'
$firstPositionOfFoo = Strings\firstPosition('foo');

// Called as a function.
echo $firstPositionOfFoo('This is when the foo begins'); // 17

// Used in a higher order function.
$array = array_map($firstPositionOfFoo, ['This is when the foo begins', 'is bar']);
print_r($array); // [17, null]




// An offset of where to start the search can be passed.
$firstPositionOfFoo = Strings\firstPosition('a', 5);
print $firstPositionOfFoo('abcdefghijka'); // 11




// The search can be case sensitive or insensitive. (SENSITIVE by default)
$firstPositionOfFoo = Strings\firstPosition('C', 0, STRINGS_CASE_INSENSITIVE);
print $firstPositionOfFoo('abcdefghijka'); // 2

Curried

This can be called inline using currying.

print Strings\firstPosition('foo')( 'This is when the foo begins'); // 17

Inlined with Higher Order Function

If you are not planning on reusing the Closure created, you can just call it inline with a higher order function as its callable.

$array = array_map(Strings\firstPosition('foo'), ['This is when the foo begins', 'is bar']);
print_r($array); // [17, null]

Details

Strings Functions

Releated String analysis Functions