2011-11-23 35 views
1

編輯:我試圖將字符串中符合以下,嘗試匹配這個正則表達式:PHP

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

無濟於事,幫助感謝!

感謝

+0

可不可以給的東西'$ expression'可能看起來像一些例子?你的格式與你的正則表達式看起來很不一樣,我認爲他們中的一個肯定是錯的。 – ruakh

回答

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

$結果[1]現在會包含一年

+0

對不起,我沒有澄清..只是尋找「年」的表達式... – algorithmicCoder

+0

更新的解決方案。 – jancha

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)以您想要的任何格式獲取它。 ex:

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

對不起,請參閱編輯 – algorithmicCoder

+0

@algorithmicCoder您仍然可以使用此方法獲取年份 – Ibu

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 
0

我得到這個工作:

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