简体   繁体   English

PHP:带有preg_match的正则表达式

[英]PHP: regular expression with preg_match

I am new to php and learning regular expressions. 我是php新手,正在学习正则表达式。 I am trying to use preg_match to convert a standard time to military time. 我正在尝试使用preg_match将标准时间转换为军事时间。 The data coming in is in the format "September 6, 1991 at 6:23PM." 输入的数据格式为“ 1991年9月6日下午6:23”。 Elsewhere in the code I have already used regular expressions to break the data into an array with elements "Month," "Day," "Year," "Hour," and "Minutes." 在代码的其他地方,我已经使用正则表达式将数据分成具有“月”,“日”,“年”,“小时”和“分钟”元素的数组。 I am trying to tell the program to look at the data and if it ends in PM add 12 to the "Hour" element. 我试图告诉程序查看数据,如果它以PM结尾,则将12添加到“小时”元素中。 Here is my code: 这是我的代码:

    if (preg_match("/[A-Za-z0-9,:\s]*[PM]/", $original_data)) {
        $broken_data[$j][3]= $broken_data[$j][3] + 12;
    }

Where $original_data is a string in the format "September 6, 1991 at 6:23PM" and $broken_data is the array described above. 其中$ original_data是格式为“ 1991年9月6日下午6:23”的字符串,而$ broken_data是上述数组。 What I think the preg_match is doing (and intend for it to do) is return true if there are any number of AZ, az, 0-9, :, commas, or spaces followed by PM. 如果有任意数量的AZ,az,0-9,:,逗号或空格后跟PM,则我认为preg_match所做的事情(打算这样做)将返回true。 How is this wrong? 这怎么了

Thank you in advance! 先感谢您!

You can skip preg_match entirely and use strtotime() and str_replace() 您可以完全跳过preg_match并使用strtotime()和str_replace()

However, the format that you have breaks when you have "at" in the string, and that's why we use str_replace to get rid of it. 但是,当字符串中有“ at”时,您使用的格式会中断,这就是为什么我们使用str_replace摆脱它的原因。

// converts to "September 6, 1991 6:23PM"
$time = str_replace(" at ", " ", "September 6, 1991 at 6:23PM"); 
// You will need to change this to the format you want outputted
echo date("M d, Y H:i" , strtotime($time));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM