我想借此2012-07-16T21:00:00出修改正則表達式匹配時
<abbr title="2012-07-16T21:00:00" class="dtstart">Monday, July 16th, 2012</abbr>
的,但我有一些困難。這是我做過什麼
preg_match('/<abbr title="(.*)" \/>/i', $file_string, $time);
$time_out = $time[1];
我想借此2012-07-16T21:00:00出修改正則表達式匹配時
<abbr title="2012-07-16T21:00:00" class="dtstart">Monday, July 16th, 2012</abbr>
的,但我有一些困難。這是我做過什麼
preg_match('/<abbr title="(.*)" \/>/i', $file_string, $time);
$time_out = $time[1];
雖然我不使用這樣的正則表達式是最好的方法,它可能是在某些情況下確定的想法。
如果您使用正則表達式,這是你所需要的:
preg_match('/<abbr title="([^"]*)"/i', $file_string, $time);
看到它在這裏的行動:http://viper-7.com/qZu9tj
不幸的是,這並沒有給我任何東西在$時間 – EnexoOnoma 2012-07-31 15:16:14
@Kaoukkos - 我添加了一個演示的答案。那對你有用嗎? – 2012-07-31 15:18:55
是的!謝謝。 – EnexoOnoma 2012-07-31 17:27:28
使用
preg_match('/<abbr title="([^"]*)" \/>/i', $file_string, $time);
所以你的匹配將停止第一個< <「>>([^」]表示除了「以外的任何東西」)
或
preg_match('/<abbr title="([0-9T:-]*)" \/>/i', $file_string, $time);
更準確地說,使用組僅包含您需要捕獲的內容。 (注意「是已排除)
不幸的是這些作品都沒有。 – EnexoOnoma 2012-07-31 15:15:52
嘗試這種方式,而不是正則表達式:。
$dom = new DOMDocument;
$dom->loadXML($file_string);
$abbr = simplexml_import_dom($dom);
$time;
foreach ($abbr[0]->attributes() as $key => $value)
{
if ($key == 'title')
{
$time = $value;
break;
}
}
echo $time;
正則表達式可以用於處理這樣的事情痛苦最好使用一個解析器
的最好的辦法是使用HTML解析器,像PHP的DOM。
<?php
$html = <<<HTML
<abbr title="2012-07-16T21:00:00" class="dtstart">Monday, July 16th, 2012</abbr>
HTML;
$dom = new DOMDocument();
$dom->loadHTML($html);
$abbr = $dom->getElementsByTagName("abbr")->item(0);
$title = $abbr->getAttribute("title");
echo $title;
這甚至會工作,如果你的數據不看è xactly like:
title
之前或之後還有其他屬性。"
,'
或無)。所以,請不要使用正則表達式,因爲它會事件導致你失去理智去斬首。 <center>
忍不住爲時已晚。
請不要使用正則表達式解析HTML,因爲它會[驅動你į̷̷͚̤̤̖̦͍͗̒̈̅̄n̨͖͓̹͍͎͔͈̝͐ͪ͛̄͛ṣ̷̵̞̦ͤ̅̉̋ͪ͑͛ͥ͜a̷̘͖̮͔͎͛̇̏̒͆̆͘n͇͔̤̼͙̩͖̭ͤ͋̉͌͟eͥ͒͆ͧͨ̽͞҉̹͍̳̻͢](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454 #1732454)。改爲使用[HTML解析器](http://stackoverflow.com/questions/292926/robust-mature-html-parser-for-php)。 – 2012-07-31 15:11:57