PHP正则表达式获取自定义文档参数
可以从此类文件中获得:PHP正则表达式获取自定义文档参数,php,regex,annotations,Php,Regex,Annotations,可以从此类文件中获得: /** * @mapping(table='example') */ class Example { 输出如下: Array ( [table] => 'example' ) 使用regex使用多个逗号分隔的参数,比如@mapping(table='example',else=something,…)等等 这实际上是我当前用于解析反射类文档内容的代码,它在堆栈中的某个地方找到。我对regex没有那么强,谢谢你的帮助 function parseAnnot
/**
* @mapping(table='example')
*/
class Example {
输出如下:
Array
(
[table] => 'example'
)
使用regex使用多个逗号分隔的参数,比如@mapping(table='example',else=something,…)等等
这实际上是我当前用于解析反射类文档内容的代码,它在堆栈中的某个地方找到。我对regex没有那么强,谢谢你的帮助
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*
捕获组1,匹配除([^\s=]+)
或空白字符以外的任何字符的1+倍=
逐字匹配=
捕获组2,匹配除所列字符之一之外的任何字符的1+倍([^\s,=()]+)
$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
谢谢,但不是很准确。我只是在编辑正则表达式时遇到了问题,无法输出,但我可以(通过反射)获取内容文档。您可以使用两个捕获组
(?:^/\*\*(?:\R\h\*)*\R\h*\*\h*@mapping\(|\G(?!^)),?\h*([^\s=]+=([^\s,=])
@Thefourthbird谢谢,太棒了..正是我要找的!@Thefourthbird我用来解释,解释得很好,谢谢你,先生!