Strings\lastPosition()

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

Returns a function which can be used to find the last 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\lastPosition(string $needle, int $offset = 0, int $flags = STRINGS_CASE_SENSITIVE): Closure

Returned Closure

When Strings\lastPosition() 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'
$lastPositionOfFoo = Strings\lastPosition('foo');

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

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




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




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

Curried

This can be called inline using currying.

print Strings\lastPosition('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\lastPosition('foo'), ['This is when the foo begins', 'is bar']);
print_r($array); // [17, null]

Details

Strings Functions

Releated String analysis Functions