Muhammad Osama
Muhammad Osama

Reputation: 1047

Preg_grep() Regex pattern is not working as expected

I have the following code and I'm trying to achieve an effect like this
-Remove the "-" and number from the end of the string.
-Then check if the value is matching or not.

Here's my PHP code

$usernames= array("microsoft-2","google-1","google");
$value='google';

$input = preg_quote($value, '~');
$result = preg_grep('~' . $value . '~', $usernames);

echo '<pre>';
print_r($result);
//Array
(
    [1] => google-1
    [2] => google
)


The above results are fine but the problem is If I set value as "goog" it returns the same result while I'm expecting it to return an empty erray.
The usernames are coming from database and can be a large number.

In short it should return an remove the dash and number at the end and afterwards it should check if the values are same or not. If yes, then push in results otherwise not.
Any help would be appreciated ! Many Thanks

Upvotes: 0

Views: 184

Answers (1)

ArtisticPhoenix
ArtisticPhoenix

Reputation: 21681

Add word break \b

$usernames= array("microsoft-2","google-1","google");
$value='goog';

$input = preg_quote($value, '~');
$result = preg_grep('~' . $value . '\b~', $usernames);

echo '<pre>';
print_r($result);

Output

array()

Sandbox

You can even add one to each side $result = preg_grep('~\b' . $value . '\b~', $usernames); in this case goog you only need the right one.

Upvotes: 1

Related Questions