2010-03-06 139 views
0

有人可以幫我用正則表達式模式,我可以用它來匹配鏈接元素中的文本「貓」嗎?幫助正則表達式

<A HREF="http://www.catingale2?subject=10023">Cats</A> forum 

在此先感謝!

回答

3

什麼是這樣的:

$str = '<A HREF="http://www.catingale2?subject=10023">Cats</A> forum'; 
$matches = array(); 
if (preg_match('#<a[^>]*>(.*?)</a>#i', $str, $matches)) { 
    var_dump($matches[1]); 
} 

其中給出:

string(4) "Cats" 


而且,作爲一個旁註:一般來說,使用正則表達式來 「解析」 HTML是不是相當不錯主意!

+0

可以使用哪些功能,然後獲取元素內的文本? – ajsie 2010-03-06 21:45:05

+2

我有很多部分的HTML *(比你在這裏發佈的東西更大,我的意思是)*,在許多情況下,「更好」的方法是使用實​​際的HTML解析器;像http://www.php.net/manual/en/domdocument.loadhtml.php,然後通過DOM,可能使用XPath查詢。 – 2010-03-06 21:47:32

2

無需正則表達式

$str=<<<EOF 
<A HREF="http://www.catingale2?subject=10023">Cats</A> forum 
<A HREF="http://www.catingale2?subject=10024"> 
Dogs</A> 
forum 
EOF; 
$s = explode("</A>",$str); 
foreach($s as $v){ 
    if (strpos($v,"<A HREF")!==FALSE){ 
     $t=explode(">",$v); 
     print end($t)."\n"; 
    } 
} 

輸出

# php test.php 
Cats 

Dogs 
2
<a[^>]*>([^<]*)<\/a> 

就是這樣。你也許可以矇混過關:

<a[^>]*>(.*)<\/a> 

<a[^>]*>([^<]*) 
1
$input = '<A HREF="http://www.catingale2?subject=10023">Cats</A> forum'; 
if(preg_match('{<a.*?>(.*?)</a>}i',$input,$matches)) { 
    $hyperlinked = $matches[1]; 
} 
echo $hyperlinked; // print Cats 

使用的正則表達式是:<a.*?>(.*?)</a>

說明:

<a.*?> - an opening anchor tag with any attribute. 
(.*?) - match and remember between opening anchor tag and closing anchor tag. 
</a> - closing anchor tag. 
i  - to make the entire matching case insensitive