preg_replace_callback 的意外行为
Unexpected behavior of preg_replace_callback
我认为 php 的 preg_replace_callback 函数存在运行时问题:
$a = [
'test.db',
'WhatsApp Image 2021-10-21 at 18.52.14.jpeg',
'WhatsApp Image 2021-10-21 at 18.52.15.jpeg',
'WhatsApp Image 2021-10-21 at 18.52.16.jpeg',
'WhatsApp Image 2021-10-21 at 18.52.18 (1).jpeg',
];
$callback = function ($matches) {
return $matches[0];
};
$c = preg_replace_callback('/.*\.[jp][pn]e?g/i', $callback, $a );
print_r($c);
return :
Array
(
[0] => test.db
[1] => WhatsApp Image 2021-10-21 at 18.52.14.jpeg
[2] => WhatsApp Image 2021-10-21 at 18.52.15.jpeg
[3] => WhatsApp Image 2021-10-21 at 18.52.16.jpeg
[4] => WhatsApp Image 2021-10-21 at 18.52.18 (1).jpeg
)
为什么 test.db 仍然存在,即使当我解析 return $matches[0] 它永远不适合里面?
preg_replace_callback
对数组中的每一项进行替换,但如果没有可替换的内容,它仍然 returns 元素不变。
preg_filter
就是你所需要的。
preg_filter()
is identical to preg_replace()
except it only returns the (possibly transformed) subjects where there was a match.
旁注:/.*\.[jp][pn]e?g/i
将匹配 foo.jpg.exe
。您可能需要 /.*\.[jp][pn]e?g$/i
。
我认为 php 的 preg_replace_callback 函数存在运行时问题:
$a = [
'test.db',
'WhatsApp Image 2021-10-21 at 18.52.14.jpeg',
'WhatsApp Image 2021-10-21 at 18.52.15.jpeg',
'WhatsApp Image 2021-10-21 at 18.52.16.jpeg',
'WhatsApp Image 2021-10-21 at 18.52.18 (1).jpeg',
];
$callback = function ($matches) {
return $matches[0];
};
$c = preg_replace_callback('/.*\.[jp][pn]e?g/i', $callback, $a );
print_r($c);
return :
Array
(
[0] => test.db
[1] => WhatsApp Image 2021-10-21 at 18.52.14.jpeg
[2] => WhatsApp Image 2021-10-21 at 18.52.15.jpeg
[3] => WhatsApp Image 2021-10-21 at 18.52.16.jpeg
[4] => WhatsApp Image 2021-10-21 at 18.52.18 (1).jpeg
)
为什么 test.db 仍然存在,即使当我解析 return $matches[0] 它永远不适合里面?
preg_replace_callback
对数组中的每一项进行替换,但如果没有可替换的内容,它仍然 returns 元素不变。
preg_filter
就是你所需要的。
preg_filter()
is identical topreg_replace()
except it only returns the (possibly transformed) subjects where there was a match.
旁注:/.*\.[jp][pn]e?g/i
将匹配 foo.jpg.exe
。您可能需要 /.*\.[jp][pn]e?g$/i
。