试图匹配这个正则表达式:PHP

时间:2011-11-23 01:53:21

标签: php regex

编辑:我正在尝试匹配

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

AM也许pmtimezone可能是pst等年份总是20岁

我试过了:

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

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

由于

5 个答案:

答案 0 :(得分:0)

你应该反斜杠“/”符号。并确保在表达式中有前导和尾随斜杠,例如

$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]中找到。


UPD

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]现在将包含年份

答案 1 :(得分:0)

尝试单独获取此字符串:

$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);

答案 2 :(得分:0)

我在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

答案 3 :(得分:0)

我让这个工作:

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

答案 4 :(得分:0)

提取这一年的事情怎么样?

$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";

Demo