2015-10-31 61 views
0

我有此数组:array_filter()返回一个空数组

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' 

这个代码来获取的名称中包含 “my_custom_links”(而不是 “my_come_other_custom_links”)

<?php 


     $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>"; 
    ?> 
链接

我应该得到一个有3个项目的数组,但我得到一个空数组。

回答

1

您的正常表达是错误的。

preg_match("/^my_custom_links$/" 

只会匹配字符串,即my_custom_links。将其更改为

preg_match("/my_custom_links/" 
1

试试这个:

$urls = array (
    0 => 'http://example.com/site.xml' , 
    1 => 'http://example.com/my_custom_links_part1.xml' , 
    2 => 'http://example.com/my_custom_links_part2.xml' , 
    3 => 'http://example.com/my_custom_links_part3.xml', 
    4 => 'http://example.com/my_some_other_custom_links_part1.xml'); 

    $matches = array_filter($urls, function($var) { return preg_match("/example.com/", $var); }); 

    echo "<pre>"; 
    print_r($urls); // will output all links 
    echo "</pre>"; 

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

你的正则表达式是不正确的,它会检查这些字符串这^(starts)$(ends)my_custom_links

^my_custom_links$ 

它应该是简单的

\bmy_custom_links 
1

你的代码没问题,唯一错的是你的正则表达式。 它不起作用的原因是因为你在开始时有这个^这意味着在它的开始处匹配指定的值,然后你有$这意味着在指定的字符串值的末尾匹配该字符串。

使用这个代替

preg_match("/my_custom_links/" .. rest of the code 
相关问题