如何在php中使用preg_match获取子字符串直到特定字符?

时间:2015-04-24 20:32:54

标签: php regex string preg-match

假设我有这些变化:

1:Today is a beautiful day (Monday)

2:Today is a beautiful day

我想获得Today is a beautiful day

我正在尝试preg_match('/(?=(^\w+.+))$|(?=(^\w+.+)\s\())/ui', $string, $matches)但没有成功。

1 个答案:

答案 0 :(得分:0)

您可以尝试将preg_match_allmultiline选项一起使用,如下所示:

^[^(]+(?=$|\s)

See demo

这是sample program

<?php
   $re = "/^[^(]+(?=$|\s)/ui";
   $str = "Today is a beautiful day (Monday)"; 
   preg_match_all($re, $str, $matches);
   print_r($matches);
?>

输出:

Array                                                                                                                                                               
(                                                                                                                                                                   
    [0] => Array                                                                                                                                                    
        (                                                                                                                                                           
            [0] => Today is a beautiful day                                                                                                                                                                                                                                           
        )                                                                                                                                                           

)

免责声明:根据您的反馈,我正在将正则表达式行从$re = "/^[^(]+(?=$|\\s)/m";更改为$re = "/^[^(]+(?=$|\s)/ui";,因为它适用于您。