Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 正则表达式对此进行修复?[延期]_Php_Regex - Fatal编程技术网

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