I've written this class with one static method that read annotations and convert them in one array. So, this code:
/**
* @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();
will output this:
Array ( [MyAnnotation] => Array ( [attr1] => value [attr2] => value ) );
Can someone help me optimizing this code using regular expressions? I am not able to write good code with regex. My code works fine, but I dont like it!
/**
* @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]);
}
}
}
}
You can use php function preg_match
, it will store matched substring in parenthesis (.*)
to $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];
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.