Strings\firstSubString()

transformer returns Closure pure
(string, int) → (string → string)
At a glance — Extract the text before or after the first match. Controlled by the STRINGS_BEFORE_NEEDLE / STRINGS_AFTER_NEEDLE flag. Wraps strstr().

Creates a function which allows for finding the first instance of a substring in string. Can then return all chars after or before the first occurrence. Can be set to be case sensitive or insensitive. The created function can then reused over any string, or used as part of a Higher Order Function such as array_map().

/**
  * @param string $needle The substring to look for.
  * @param int $flags Possible flags below.
  * @return Closure(string):string
  */
Strings\firstSubString(string $needle, int $flags = STRINGS_CASE_SENSITIVE | STRINGS_AFTER_NEEDLE): Closure

Returned Closure

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

/**
 * @param string $haystack The haystack to look through.
 * @return string
 */
$function (string $haystack): string

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 a closure which can get all text before foo and one that gets all text after foo.
$beforeFoo = Strings\firstSubString('foo', STRINGS_BEFORE_NEEDLE);
$afterFoo = Strings\firstSubString('foo', STRINGS_AFTER_NEEDLE);

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

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


// Case insensitive can be set by passing the flag.
$beforeFoo = Strings\firstSubString('foo', STRINGS_BEFORE_NEEDLE | STRINGS_CASE_INSENSITIVE);
echo $beforeFoo('This is when the Foo begins'); // 'This is when the '

Curried

This can be called inline using currying.

echo Strings\firstSubString('foo', STRINGS_BEFORE_NEEDLE)('This is when the foo begins'); // 'This is when the '

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\firstSubString('foo', STRINGS_BEFORE_NEEDLE), 
 ['This is when the foo begins', 'not foo']
);
print_r($array); // ['This is when the ', 'not ']

Details

Strings Functions

Releated String manipulation Functions