php 将值保存在一个平面数组中,其中所需的子字符串是区分大小写的

apeeds0o  于 5个月前  发布在  PHP
关注(0)|答案(5)|浏览(40)

我有这个数组:

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”)

$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个元素的数组,但我得到的是一个空数组。

vfhzx4xs

vfhzx4xs1#

你的正则表达式是错误的。

preg_match("/^my_custom_links$/"

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

preg_match("/my_custom_links/"

e37o9pze

e37o9pze2#

试试这个:

$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>";

字符串

kiz8lqtg

kiz8lqtg3#

您的正则表达式不正确,因为它只检查^(starts)$(ends)my_custom_links的字符串

^my_custom_links$

字符串
它应该是简单的

\bmy_custom_links

uqjltbpv

uqjltbpv4#

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

preg_match("/my_custom_links/" .. rest of the code

字符串

yc0p9oo0

yc0p9oo05#

因为你是通过文字/非动态模式过滤的,所以没有真实的理由使用正则表达式。使用array_filter()str_contains()来保留所有包含所需子字符串的值。(Demo

$needle = 'my_custom_links';
var_export(
    array_filter(
        $array,
        fn($haystack) => str_contains($haystack, $needle)
    )
);

字符串
输出量:

array (
  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',
)


事实上,将array_filter()preg_match()一起使用实际上是一种反模式--这应该总是被preg_grep()所取代,它使用正则表达式来过滤值。如果您的逻辑需要不区分大小写、字符串锚的开始/结束、单词边界、多字节支持或其他动态需求,正则表达式将是合适的。

相关问题