如何在 php 中使用 preg_match 获取特定字符之前的子字符串?

How to get a substring until a specific character with preg_match in php?

假设我有这些变化:

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) 但没有成功。

您可以尝试使用 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";,因为它适合您。