我用一个静态方法编写了这个类,该方法读取注释并将它们转换为一个数组。所以,这段代码:
/**
* @MyAnnotation(attr1=value,attr2=value);
*/
class MyClass
{
public static function readMyAnnotation()
{
$classComment = (new ReflectionClass(get_class()))->getDocComment();
$comments = explode("\n", $classComment);
foreach ($comments as $item) {
if(strpos($item, "@")) {
$comment = explode("@", $item);
$annotation = explode(")", $comment[1])[0];
$annotationName = explode("(", $annotation)[0];
$annotationValue = explode("(", $annotation)[1];
$annotationParams = explode(",", $annotationValue);
$params = [];
foreach ($annotationParams as $item) {
$params[explode("=", $item)[0]] = explode("=", $item)[1];
}
print_r([$annotationName => $params]);
}
}
}
}
MyClass::readMyAnnotation();
将输出:
Array ( [MyAnnotation] => Array ( [attr1] => value [attr2] => value ) );
有人可以帮助我使用正则表达式优化此代码吗?我无法用正则表达式编写好的代码。我的代码工作正常,但我不喜欢它!
/**
* @MyAnnotation(attr1=value,attr2=value);
*/
class MyClass
{
public static function readMyAnnotation()
{
$classComment = (new ReflectionClass(get_class()))->getDocComment();
$comments = explode("\n", $classComment);
foreach ($comments as $item) {
if(strpos($item, "@")) {
/* ?????????????? */
print_r([$annotationName => $params]);
}
}
}
}
答案 0 :(得分:1)
您可以使用php函数preg_match
,它会将括号(.*)
中匹配的子字符串存储到$match_name[1]
:
preg_match("/\@(.*)\(/",$item,$match_name);
$annotationName = $match_name[1];
preg_match("/\((.*)\)/",$item,$match_values);
$values = explode(",",$match_values[1]);
foreach ($values as $value) {
$exploded = explode("=", $value);
$params[$exploded[0]] = $exploded[1];
}