Search code examples
phparrayssubstringfilteringcase-sensitive

Keep values in a flat array where a desired substring is case-sensitively found


I have this array:

array 
  0 => string 'http://example.com/site.xml' 
  1 => string 'http://example.com/my_custom_links_part1.xml' 
  2 => string 'http://example.com/my_custom_links_part2.xml' 
  3 => string 'http://example.com/my_custom_links_part3.xml'
  4 => string 'http://example.com/my_some_other_custom_links_part1.xml' 

and this code to get the links that contain "my_custom_links" in their name (but not "my_come_other_custom_links")

$matches = array_filter($urls, function($var) { return preg_match("/^my_custom_links$/", $var); });
        
echo "<pre>";
print_r($urls); // will output all links
echo "</pre>";

echo "<pre>";
print_r($matches); // will output an empty array
echo "</pre>";

I should get an array with 3 items but I am getting an empty array.


Solution

  • Your regular expression is wrong.

    preg_match("/^my_custom_links$/"
    

    will match only string which is my_custom_links. Change it to

    preg_match("/my_custom_links/"