Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/jquery-ui/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 正则表达式模式和可选匹配_Php_Regex_Preg Match All - Fatal编程技术网

Php 正则表达式模式和可选匹配

Php 正则表达式模式和可选匹配,php,regex,preg-match-all,Php,Regex,Preg Match All,我对正则表达式模式和可选匹配有问题。基本上,我尝试从包含工作时间的字符串中提取信息,可以是以下3种形式: $d1 = 'Fr: 9-12;'; $d2 = 'Mo: 9-12 und 15-18; alle 14 Tage spez. Migräneberatung bis 20 Uhr;'; $d3 = 'Mo: 9-12; alle 14 Tage spez. Migräneberatung bis 20 Uhr;'; $regex = ' / (Mo|Di|Mi|

我对正则表达式模式和可选匹配有问题。基本上,我尝试从包含工作时间的字符串中提取信息,可以是以下3种形式:

$d1 = 'Fr: 9-12;';
$d2 = 'Mo: 9-12 und 15-18; alle 14 Tage spez. Migräneberatung bis 20 Uhr;';
$d3 = 'Mo: 9-12; alle 14 Tage spez. Migräneberatung bis 20 Uhr;';

$regex = '
    /
        (Mo|Di|Mi|Do|Fr|Sa|So)+:          # day follow by colon
            \s+?                          # a optional space
        (\d+)\-(\d+)                      # time from - to
        (?:\s+?und\s+?(\d+)\-(\d+))       # optional time from - to
            ;                               
        (?:([^;]+))                       # optional addt info
    /x';

$rc = preg_match_all($regex, $d2, $m);

print_r($m);
字符串
$d2
正常工作,我获得了所有预期匹配,但字符串
$d1
$d3
不匹配。我尝试了第二次部分和附加信息文本的可选分组,但它不起作用。我得到的是空的火柴。我看不出缺陷

我想使用
preg_match_all
来获取上述子字符串的所有出现情况,因为它是一个大字符串,从星期一到星期天,上述子字符串的形式为每天
$d1-$d3
。我不知道是否也可以使用分号作为子字符串的结束标记,这就是为什么我尝试将其与
([^;]+)
匹配的原因。 如果这不起作用,我可以选择另一个分隔符来标记一天子字符串的结束,只需首先拆分大字符串并在循环中匹配子字符串


谢谢你给我任何提示!提前感谢您的帮助

我可能错了,但这似乎有效:

$regex = '
    /
        (Mo|Di|Mi|Do|Fr|Sa|So):           # day follow by colon
            \s+?                          # a optional space
        (\d+)\-(\d+)                      # time from - to
        (?:\s+?und\s+?(\d+)\-(\d+))?      # optional time from - to
            ;
        (?:([^;]+))?                      # optional addt info
    /x';

刚刚为可选元素添加了可选性(问号)。

事实上,这就是问题所在:-/谢谢您的帮助:-)