2017-06-21 78 views
0

我需要在php中的一些正則表達式操作的幫助。PHP preg_replace鏈接獲取href和錨文本並連接它

我有字符串,例如

$string = 'This article is about something. If You want more 
<a href='http://www.google.com'>click here</a>. If not just close 

我想結果是這樣的:

$string = 'This article is about something. If You want more click here - 
http://google.com. If not just close 

我怎麼能做到這一點在PHP?我不能用簡單的HTML解析器和其他庫

請幫助,我不知道如何實現這一目標

+1

[RegEx match open tags not except XHTML self-contained tags](https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags) –

+0

*「我不能使用簡單的html解析器和其他庫」* ...甚至沒有內置的'DOMDocument'?你很可能在RegExp和HTML上遇到困難...... – CD001

+0

'我不能使用簡單的html解析器和其他庫,爲什麼不呢?你可以使用'preg_replace'?如果你可以使用它,你有沒有嘗試過? – chris85

回答

0

真的無法找到一個方法來做到這一切在一個步驟,但這應該工作:

<?php 
$link = "This article is about something. If You want more <a href='http://www.google.com'>click here</a>. If not just close"; 
preg_match_all('/<a[^>]+href=([\'"])(.+?)\1[^>]*>/i', $link, $result); // Grab the href 
$link = preg_replace("/<a href=.*?>(.*?)<\/a>/",$result[2][0],$link); // remove a tag and replace with href value 
echo $link; 
// output: This article is about something. If You want more http://www.google.com. If not just close 
    ?> 
+0

謝謝,問題是我真的需要錨文本(點擊這裏),第二個問題是字符串可以包含多個鏈接。您的代碼會將所有鏈接替換爲首次發生的href。 –