Strings\containsPattern()

predicate returns Closure returns bool pure
string → (string → bool)
At a glance — Bind a regex; the returned Closure asks 'does this string match?'. Wraps preg_match().

Returns a function which can be used to check if a string contains a defined regex expression. The created function can then reused over any string, or used as part of a Higher Order Function such as array_filter().

/**
  * @param string $pattern The pattern to look for.
  * @return Closure(string):bool
  */
 Strings\containsPattern(string $pattern): Closure

Returned Closure

When Strings\containsPattern() 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

Examples

Partial Application

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

// Create function to check if a string contains 'foo' but not 'bar'
$containsFooNotBar = Strings\containsPattern('/(?!.*bar)(?=.*foo)^(\w+)$/');

// Called as a function.
$containsFooNotBar('its foo'); // true
$containsFooNotBar('its bar'); // false
$containsFooNotBar('its bar and foo'); // false

// Used in a higher order function.
$array = array_filter(['its foo', 'its bar'], $containsFooNotBar);
print_r($array); // ['its foo']

Curried

This can be called inline using currying.

Strings\containsPattern('/(?!.*bar)(?=.*foo)^(\w+)$/')('its foo'); // true
Strings\containsPattern('/(?!.*bar)(?=.*foo)^(\w+)$/')('its bar'); // false
Strings\containsPattern('/(?!.*bar)(?=.*foo)^(\w+)$/')('its bar and foo'); // false

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_filter(['its foo', 'its bar'], Strings\containsPattern('/(?!.*bar)(?=.*foo)^(\w+)$/'));

print_r($array); // ['its foo']

Details

Strings Functions

Releated String predicate Functions