使用字符串中的正则表达式提取创建日期,上次修改日期和方法名称

问题描述 投票:0回答:1

下面一部分代码存储在一个名为的文件中 Website.php

<?php
namespace AdamInChains;
class Website
{

/**
 * 02.14.2019 13:24:59 creation date
 * 02.14.2019 13:28:23 last modified date
 * @param array $meta_tags
 *
 * @return string
 */
public function index(array $meta_tags) : string{}

/**
 * 02.14.2019 13:45:59 creation date
 * 02.14.2019 13:49:21 last modified date
 * @param array $meta_tags
 *
 * @return string
 */
public function about(array $meta_tags) : string{}

/**
 * 02.14.2019 14:01:52 creation date
 * 02.14.2019 14:33:01 last modified date
 * @param array $meta_tags
 *
 * @return string
 */
public function contact(array $meta_tags) : string{}
}

我需要提取创建日期和上次修改日期

然后以这种方式将正则表达式结果存储到一个数组中

$array = [
    // method name
    "index" => [
        "creation_date"=>"02.14.2019 14:01:52",
        "last_modified_date"=>"02.14.2019 13:28:23"
    ]
];

基本上当用户,在这种情况下AdamInChains并且你可以从命名空间声明中看到这个,在他的网站上创建一个新页面时,一个新方法,被声明为输入页面名称,被添加到类中,日期被添加到doc方法评论。

到目前为止,我只能提取方法名称(参见下面的代码),但其他任务没有成功。

// regex pattern
$re = '/public function.(\w{0,})/m';
// file 'Website.php'
$str = file_get_contents('Website.php');

preg_match_all($re, $str, $matches);

// Print the entire match result
var_dump($matches);

This is the var_dump results and I'm happy with it

任何人?

php regex
1个回答
1
投票

这是一个你可以使用的正则表达式:

(?<creationDate>\d{2}\.\d{2}\.\d{4}\s\d{2}:\d{2}:\d{2})\screation\sdate[^\Z]*?(?<modifiedDate>\d{2}\.\d{2}\.\d{4}\s\d{2}:\d{2}:\d{2})\slast\smodified\sdate[^\Z]*?public\sfunction\s(?<methodName>[^\(\s]+)

https://regex101.com/r/7wrrhj/1

© www.soinside.com 2019 - 2024. All rights reserved.