PHP 正则表达式获取自定义文档参数
PHP Regex get custom doc params
可以从这个 class 文档中得到:
/**
* @mapping(table='example')
*/
class Example {
输出如下:
Array
(
[table] => 'example'
)
等等,使用正则表达式的多个逗号分隔参数,如@mapping(table='example', else=something,...)?
这实际上是我当前用于解析我的反射 class 文档内容的代码,它是在堆栈的某处找到的。我不太擅长正则表达式,感谢您的帮助!
function parseAnnotations($doc)
{
preg_match_all('/@([a-z]+?)\s+(.*?)\n/i', $doc, $annotations);
if(!isset($annotations[1]) OR count($annotations[1]) == 0){
return [];
}
return array_combine(array_map("trim",$annotations[1]), array_map("trim",$annotations[2]));
}
对于示例数据,您可以使用 \G
锚点来获得连续匹配。
(?:^/\*\*(?:\R\h+\*)*\R\h*\*\h*@mapping\(|\G(?!^)),?\h*([^\s=]+)=([^\s,=()]+)
(?:
非捕获组
^
字符串开头
/\*\*
匹配 **
(?:\R\h*\*)*
可选择重复匹配换行符和 *
\R\h*\*\h*@mapping\(
匹配一个换行符,可选的空格 *
可选的空格和@mapping
|
或
\G(?!^)
断言上一场比赛结束时的位置,而不是开始
),?
关闭非捕获组并匹配一个可选的逗号
\h*
匹配可选的水平空白字符
([^\s=]+)
捕获 组 1,匹配除 =
或空白字符 之外的任何字符 1+ 次
=
字面匹配
([^\s,=()]+)
捕获 组 2,匹配除列出的字符之一以外的任何字符 1+ 次
例子
$re = '~(?:^/\*\*(?:\R\h\*)*\R\h*\*\h*@mapping\(|\G(?!^)),?\h*([^\s=]+)=([^\s,=()]+)~m';
$str = '/**
* @mapping(table=\'example\')
*/
class Example {
/**
* @mapping(table2=\'example2\', else=something,...)
*/
class Example {';
preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
foreach ($matches as $match) {
echo sprintf("%s --> %s", $match[1], $match[2]) . PHP_EOL;
}
输出
table --> 'example'
table2 --> 'example2'
else --> something
可以从这个 class 文档中得到:
/**
* @mapping(table='example')
*/
class Example {
输出如下:
Array
(
[table] => 'example'
)
等等,使用正则表达式的多个逗号分隔参数,如@mapping(table='example', else=something,...)?
这实际上是我当前用于解析我的反射 class 文档内容的代码,它是在堆栈的某处找到的。我不太擅长正则表达式,感谢您的帮助!
function parseAnnotations($doc)
{
preg_match_all('/@([a-z]+?)\s+(.*?)\n/i', $doc, $annotations);
if(!isset($annotations[1]) OR count($annotations[1]) == 0){
return [];
}
return array_combine(array_map("trim",$annotations[1]), array_map("trim",$annotations[2]));
}
对于示例数据,您可以使用 \G
锚点来获得连续匹配。
(?:^/\*\*(?:\R\h+\*)*\R\h*\*\h*@mapping\(|\G(?!^)),?\h*([^\s=]+)=([^\s,=()]+)
(?:
非捕获组^
字符串开头/\*\*
匹配**
(?:\R\h*\*)*
可选择重复匹配换行符和*
\R\h*\*\h*@mapping\(
匹配一个换行符,可选的空格*
可选的空格和@mapping|
或\G(?!^)
断言上一场比赛结束时的位置,而不是开始
),?
关闭非捕获组并匹配一个可选的逗号\h*
匹配可选的水平空白字符([^\s=]+)
捕获 组 1,匹配除=
或空白字符 之外的任何字符 1+ 次
=
字面匹配([^\s,=()]+)
捕获 组 2,匹配除列出的字符之一以外的任何字符 1+ 次
例子
$re = '~(?:^/\*\*(?:\R\h\*)*\R\h*\*\h*@mapping\(|\G(?!^)),?\h*([^\s=]+)=([^\s,=()]+)~m';
$str = '/**
* @mapping(table=\'example\')
*/
class Example {
/**
* @mapping(table2=\'example2\', else=something,...)
*/
class Example {';
preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
foreach ($matches as $match) {
echo sprintf("%s --> %s", $match[1], $match[2]) . PHP_EOL;
}
输出
table --> 'example'
table2 --> 'example2'
else --> something