2015-10-31 3 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 
Смежные вопросы