Core\Str::contains
Core\Str::contains(string $haystack, string $needle): boolCore\Str::contains( string $haystack, string $needle, ): bool
Checks whether a piece of text appears anywhere in a string.
Core\Str::contains returns true when the text is found, and false when it is not. The position does not matter: the start, the middle and the end all count.
The search is case-sensitive, so "Error" does not find "error". To ignore upper and lower case, change both strings to lower case with Core\Str::lower first. An empty search text is found in every string, so the result is true.
Core\Str::contains only tells you whether the text is there. To find where it is, use Core\Str::indexOf. To count how many times it appears, use Core\Str::countOf.
The examples below search a short string, search without caring about upper and lower case, and keep only the lines of a log that report an error.
Parameters
$haystackstringThe string to search in.$needlestringThe text to search for. The search is case-sensitive.
Return value
Returns bool. true when $needle is in $haystack, otherwise false. An empty $needle is in every string, so the result is true.
Examples
Find a word
<?nvs// Shows how to check whether a string contains a piece of text.
string $subject = 'Your order #1042 has shipped';
// "#1042" is in the middle of the string. This prints `true`.echo Core\Str::contains($subject, '#1042') ? 'true' : 'false', "\n";
// "cancelled" is not in the string. This prints `false`.echo Core\Str::contains($subject, 'cancelled') ? 'true' : 'false', "\n";
// The search is case-sensitive, so "your" does not find "Your".// This prints `false`.echo Core\Str::contains($subject, 'your') ? 'true' : 'false', "\n";
// An empty search text is in every string. This prints `true`.echo Core\Str::contains($subject, '') ? 'true' : 'false', "\n";truefalsefalsetrueIgnore upper and lower case
<?nvs// Shows how to search without caring about upper and lower case.
array<string> $titles = ['Learning NOVIS', 'novis for beginners', 'A Guide to Rust'];string $search = 'Novis';
foreach ($titles as string $title) { // `Core\Str::lower` changes both strings to lower case before the search. // This prints `yes` for the first two titles and `no` for the third. bool $found = Core\Str::contains(Core\Str::lower($title), Core\Str::lower($search)); echo $title, ': ', $found ? 'yes' : 'no', "\n";}Learning NOVIS: yesnovis for beginners: yesA Guide to Rust: noErrors in a log
<?nvs// Shows how to keep only the lines of a log file that report an error.
string $log = "10:00 INFO server started\n" . "10:02 ERROR database is not reachable\n" . "10:03 INFO retrying\n" . "10:05 ERROR disk is full\n";
uint $errors = 0;foreach (Core\Str::lines($log) as string $line) { if (Core\Str::contains($line, ' ERROR ')) { echo $line, "\n"; $errors = $errors + 1; }}// Two lines contain " ERROR ". This prints `2 errors`.echo $errors, " errors\n";10:02 ERROR database is not reachable10:05 ERROR disk is full2 errors