Php 正则表达式对此进行修复?[延期]
很抱歉,我应该在前面的问题中问这个问题: 这是一个延伸问题: 从以下数组中的元素:Php 正则表达式对此进行修复?[延期],php,regex,Php,Regex,很抱歉,我应该在前面的问题中问这个问题: 这是一个延伸问题: 从以下数组中的元素: http://example.com/apps/1235554/ http://example.com/apps/apple/ http://example.com/apps/126734 http://example.com/images/a.jpg 我使用以下方法将apps/{number}/和apps/{number}分开: foreach ($urls as $url) { if (preg_m
http://example.com/apps/1235554/
http://example.com/apps/apple/
http://example.com/apps/126734
http://example.com/images/a.jpg
我使用以下方法将apps/{number}/
和apps/{number}
分开:
foreach ($urls as $url)
{
if (preg_match('~apps/[0-9]+(/|$)~', $url)) echo $url;
}
现在,如何将{number}
推送到具有相同正则表达式的另一个数组?将数组作为包含匹配项的第三个参数。使用()
创建一个捕获组,然后该数字将包含在$matches[1]
中:
$numbers = array();
foreach ($urls as $url)
{
$matches = array();
if (preg_match('~apps/([0-9]+)~', $url, $matches)) { // note the "( )" in the regex
echo $url;
$numbers[] = $matches[1];
}
}
仅供参考,
$matches[0]
包含文档中描述的整个匹配模式。当然,您可以随意命名数组。如果目标是找到匹配的URL,您可以使用preg\u grep()
:
$urls = array(
'http://example.com/apps/1235554/',
'http://example.com/apps/apple/',
'http://example.com/apps/126734',
'http://example.com/images/a.jpg',
);
$urls = preg_grep('!apps/(\d+)/?$!', $urls);
print_r($urls);