0

How can I case insensitive test if a string contains another string as a single word? The needle is not allowed to have any other letters [a-z] around it.

Here are a few examples:

$needle = 'Test';

$haystack1 = 'This is a_test'; // true
$haystack2 = 'This is a test'; // true
$haystack3 = 'Test this is'; // true
$haystack4 = 'Another Test as example'; // true
$haystack5 = 'This is atest'; // false

2 Answers 2

2

I've got this regex /(?<=[^a-z]|^)text(?=[^a-z]|$)/i.

It means: check for text without [a-z] or text start before, and without [a-z] or text end after. The /i is for incasesensible.

Note that it matches when there is a number after 'text', if you want to exclude numbers from matching the discartion group becomes [^a-z^\d] (\d for digits).

EDIT: With a bit more of research, I found that there is a better way to do that. It's called word boundaries, and consists in just add \b before and after your word: /\btext\b/i.

2

Thanks to @Pakoco I found a solution:

if (preg_match('/^(?i)(?=.*?\b' . $needle . '\b).*/', $haystack) === 1) {
    // do stuff
}

For completion here the regex if the needle has to be at the beginning:

if (preg_match('/^(?i)(' . $needle . '\b).*/', $haystack) === 1) {
    // do stuff
}

And here if the needle has to be at the end:

if (preg_match('/(?i)(\b' . $needle . ')$/', $haystack) === 1) {
    // do stuff
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.