2011-08-31 59 views
2

這是我的代碼:的preg_replace需要幫助的表達

$string = '<a href="http://www.mysite.com/test" class="prevlink">&laquo; Previous</a><a href=\'http://www.mysite.com/test/\' class=\'page\'>1</a><span class=\'current\'>2</span><a href=\'http://www.mysite.com/test/page/3/\' class=\'page\'>3</a><a href=\'http://www.mysite.com/test/page/4/\' class=\'page\'>4</a><a href="http://www.mysite.com/test/page/3/" class="nextlink">Next &raquo;</a>'; 
$string = htmlspecialchars($string, ENT_COMPAT, 'UTF-8'); 
$string = preg_replace('@(&lt;a).*?(nextlink)@s', '', $string); 
    echo $string; 

我試圖刪除最後一個環節:

<a href="http://www.mysite.com/test/page/3/" class="nextlink">Next &raquo;</a>'; 

我的電流輸出:

">Next &raquo;</a> 

它消除了一切從頭開始。 我希望它只能刪除strpos,這是可能的preg_replace和如何? 謝謝。

回答

1

一個相當棘手的問題解決

第一關, 的。*?不會像你期待的那樣匹配。

它從左邊開始找到< a的第一個匹配,然後搜索直到找到nextlink,它實質上是拾取整個字符串。

爲正則表達式工作,因爲你想,那就需要從右邊第一個匹配,並通過串向後工作,發現最小的(非貪婪)比賽

我看不到任何修飾這將做到這一點 ,所以我選擇了每一個環節上的回調,這將檢查並刪除它

<?php 
$string = '<a href="http://www.mysite.com/test" class="prevlink">&laquo; Previous</a><a href=\'http://www.mysite.com/test/\' class=\'page\'>1</a><span class=\'current\'>2</span><a href=\'http://www.mysite.com/test/page/3/\' class=\'page\'>3</a><a href=\'http://www.mysite.com/test/page/4/\' class=\'page\'>4</a><a href="http://www.mysite.com/test/page/3/" class="nextlink">Next &raquo;</a>'; 

echo "RAW: $string\r\n\r\n"; 

$string = htmlspecialchars($string, ENT_COMPAT, 'UTF-8'); 

echo "SRC: $string\r\n\r\n"; 


    $string = preg_replace_callback(
     '@&lt\;a.+?&lt;/a&gt;@', 
     'remove_nextlink', 
     $string 
    ); 


function remove_nextlink($matches) { 

    // if you want to see each line as it works, uncomment this 
    // echo "L: $matches[0]\r\n\r\n"; 

    if (strpos($matches[0], 'nextlink') === FALSE) { 
     return $matches[0]; // doesn't contain nextlink, put original string back 
    } else { 
     return ''; // contains nextlink, replace with blank 
    } 
}  

echo "PROCESSED: $string\r\n\r\n"; 
+0

感謝您的解釋,我必須學習pregEx它似乎非常強大。代碼工作,非常感謝。 =) – Muazam

+0

這不是最優雅的解決方案,但它確實有效,編寫正則表達式來處理html始終是困難的工作 – bumperbox

1

注意:這不是一個直接的答案,而是另一種方法的建議。

我被告知過一次;如果你能以任何其他方式做到這一點,遠離正則表達式。我不是,那是我的白鯨。你聽說過phpQuery嗎?它是用PHP實現的jQuery,非常強大。它將能夠以非常簡單的方式做你想做的事。我知道這不是正則表達式,但也許它對你有用。

如果你真的想繼續,我可以推薦http://gskinner.com/RegExr/。我認爲這是一個很棒的工具。

+0

感謝您的鏈接。我的問題解決了。 – Muazam