[英]Trying to match this regular expression: PHP
編輯:我試圖匹配下面的字符串中的年份
$expression = "BORN ON:</th><td>weekday, Month Day, Year
hr:min:sec AM timezone</td>"
可能是pm
AM
, timezone
可能是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.