phparraysregexfilteringword-boundary

Filter array to keep values containing the search word using word boundaries


I know this type of question has been asked before and I also saw those working answers. However, it's not working when there are no space between the search string and the rest of the array value. Here is my code -

$example = array ( 'ext_03.jpg', 'int_01_headlight.jpg');
$searchword = 'int_';
$matches = array_filter($example, function($var) use ($searchword) {
    return preg_match("/\b$searchword\b/i", $var);
});
echo array_values($matches)[0];`

The last value in the $example array doesn't have any space and this code doesn't work. However, if I put space after int_ it works. But I need it to work even if there are no spaces (should work when there is space too). How can I achieve that?


Solution

  • Here is the solution :

    $example = array ( 'ext_03.jpg', 'int_01_headlight.jpg');
    $searchword = 'int_';
    $matches = array_filter($example, function($var) use ($searchword) { return 
    preg_match("/\b$searchword/i", $var); });
    var_dump($matches);
    

    Remove second \b : The \b in the pattern indicates a word boundary

    Documentation : http://php.net/manual/en/function.preg-match.php

    EDIT :

    The better way is to use \A : Beginning of the string

    $example = array ( 'ext_03.jpg', 'int_01_headlight.jpg', 'ext_ int_01_headlight.jpg');
    $searchword = 'int_';
    
    // Return 2 results (wrong way)
    $matches = array_filter($example, function($var) use ($searchword) { return preg_match("/\b$searchword/i", $var); });
    var_dump($matches);
    
    // Return 1 result
    $matches = array_filter($example, function($var) use ($searchword) { return preg_match("/\A$searchword/i", $var); });
    var_dump($matches);