我用一个静态方法编写了这个类,该方法读取注释并将它们转换为一个数组。因此,这段代码:
/**
* @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]);
}
}
}
}
您可以使用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];
}