basagabi
basagabi

Reputation: 5064

PHP preg_match is not exactly matching searched string

How do you exactly find a string in a string? My code doesn't seem to work:

if ( preg_match("/\b" . $needle . "\b/", $string) )
    return 'has-error';

Given this values:

$string = 'Sub-Category is required.';
$needle = 'Category';

It returns as TRUE. It should be FALSE since what I'm looking for is the word "Category". Though the word itself is in the string, it is still not considered as it.

Thanks!

Upvotes: 0

Views: 711

Answers (4)

UrsaDK
UrsaDK

Reputation: 865

In PHP the word boundary (\b) matches in the place where word characters (\w) change into the non-word characters (\W). Letters are considered to be word characters, while - is a non-word character. Thus, a string Sub-Category has four word boundaries in it: beginning of the string, just before - character, just after it, and the end of the string.

To get back to your question, preg_match first matched against the Sub portion of the $string (and fails), then moves on and attempts to match against the Category portion of the string (and succeeds). Thus, preg_match returns TRUE, as in: match found.

In order to avoid that, you have to create a word boundary manually eg:

preg_match("(^|[^\w-])" . $needle . "([^\w-]|$)/", $string)

In the above example we manually define the word boundary as NOT (word char OR dash) while accounting for the possibility of the match taking place in the begining/end of the string.

Upvotes: 1

basagabi
basagabi

Reputation: 5064

I found the answer!

if ( preg_match("/\b[^\-]" . $needle . "/", $validationErrors) )
    return 'has-error';

Upvotes: 0

Robin
Robin

Reputation: 1216

I am not sure whether I understood your question right. But when I got it right, you want to test whether your string $string is exactly equal to your $needle (without case sensitivity)? If that is the case, I would suggest this code:

function isAeuqalB($string,$needle) {
    if(preg_match("/^".$needle."$/i",$string)) {
        return true;  
    }
    return false;
}

isAeuqalB("Category","Category"); // returns true
isAeuqalB("Sub-Category","Category"); // returns false

Your mistake is that you did miss the ^ and the $ which specifies that $string needs to be euqal to $needle from beginning until end.

Your code did only check whether the word Category was part of your $string.


A good website to check your RegEx is regex101.com.

Upvotes: 0

Matteo Pampana
Matteo Pampana

Reputation: 166

Try with this regex:

"/".$needle."/i"

So the code will be:

if ( preg_match("/" . $needle . "/i", $string) )
    return 'has-error';

Upvotes: 0

Related Questions