繁体   English   中英

尝试匹配此正则表达式:PHP

[英]Trying to match this regular expression: PHP

编辑:我试图匹配下面的字符串中的年份

   $expression = "BORN ON:</th><td>weekday, Month Day, Year 
hr:min:sec AM timezone</td>"

可能是pm AMtimezone可能是pst年份总是20左右

我试过了:

$pattern = "~BORN ON:</th><td>\w+(/20\d\d/)\w+</td>~";

无济于事,感谢您的帮助!

谢谢

您应该反斜杠“ / ”符号。 并确保您的表达式中有正斜杠和斜杠

$pattern = "~BORN ON:<\/th><td>\w+(\/20\d\d/)\w+<\/td>~";

preg_match("/...../", $where, $results);

其次,这里是更新的表达式:

preg_match("/BORN ON:<\/th><td>\w, \w [0-9]+, [0-9]+ [0-9]+:[0-9]+:[0-9]+ (AM|PM) \w <\/td>/i", $where, $results);

未经测试,但应符合您的需求。 同样,将需要显示在结果中的部分括起来-atm,如果匹配,则所有日期都可以在$ results [1]中找到。


更新

preg_match("/BORN ON:<\/th><td>(\w, \w [0-9]+, ([0-9]+) [0-9]+:[0-9]+:[0-9]+ (AM|PM) \w) <\/td>/i", $where, $results);

$ results [1]现在将包含年份

尝试单独获取此字符串:

$string_time = "weekday, Month Day, Year hr:min:sec AM timezone" ;
// you use str_replace to get it

然后使用php内置函数:

$the_time = strtotime($string_time);

现在,如果您正在寻找它,就可以随心所欲地对其进行操作。

您可以使用date("...",$string_time)以所需的任何格式获取它。 例如:

echo date("Y-m-d",$string_time);

我在Ruby中使用了它。 正则表达式在PHP中完全相同。 试试看。 如果您有任何问题,请告诉我。 我很乐意提供帮助。 祝好运! :)

string = "BORN ON:</th><td>weekday, Month Day, Year hr:min:sec AM timezone</td>"
regex = /<\/th><td>([^,]+)\s*,\s*([^ ]+)\s+([^,]+)\s*,\s*([^ ]+)\s+([^:]+):([^:]+):([^ ]+)\s+(AM|PM)([^<]+)<\/td>/i
if regex.match(string)
    puts "match"
    puts "#{$1} is weekday"
    puts "#{$2} is month"
    puts "#{$3} is day"
    puts "#{$4} is year"
    puts "#{$5} is hour"
    puts "#{$6} is minutes"
    puts "#{$7} is seconds"
    puts "#{$8} is Am or Pm"
    puts "#{$9} is timezone"
else
    puts "no match"
end

我得到这个工作:

"~BORN ON:</th><td>\w+, \w+ [0-9]+, ([0-9]+)~";

这样提取年份的方法怎么样?

$strs = array( 
    "BORN ON:</th><td>weekday, Month 05, 2011 hr:min:sec AM timezone</td>",
    "BORN ON:</th><td>Sunday, Jan 05, 2010 hr:min:sec AM timezone</td>",
    "BORN ON:</th><td>Tuesday, 11 05, 2019 hr:min:sec AM timezone</td>"    
);

foreach( $strs as $subject)
    if( preg_match('%BORN ON:</th><td>\w+,\s*\w+\s*\w+,\s*(\d+)\s*%im', $subject, $regs))
        echo $regs[1] . "\n";

演示版

暂无
暂无

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

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