2011-03-06 54 views
0

我希望能夠使用一些自定義信息查找並替換文本中的所有可點擊鏈接。請考慮下面的例子:PHP:使用自定義信息查找並替換可點擊(.php)鏈接

This is a sample text. Visit: http://www.microsoft.com/help.asp Sample text. Please visit http://www.mydomain.com/sometime.jpg. This is some random text. And this is some random sample text. Visit http://www.mydomain.com/help.php for more help. Visit http://www.mydomain.com/contact.php if you wish to contact us. 

在上面的文字,我希望能夠取代所有可點擊「.PHP」鏈接到類似下面:

This is a sample text. Visit: http://www.microsoft.com/help.asp Sample text. Please visit http://www.mydomain.com/sometime.jpg. This is some random text. And this is some random sample text. Visit http://www.mydomain.com/mypage.php?url=help.php for more help. Visit http://www.mydomain.com/mypage.php?url=contact.php if you wish to contact us. 

我嘗試使用的preg_replace和ereg_replace,但它不適合我。

所有幫助表示讚賞。謝謝。

回答

1

它只是在你的域名?

$str = "This is a sample text. Visit: http://www.microsoft.com/help.asp Sample text. Please visit http://www.mydomain.com/sometime.jpg. This is some random text. And this is some random sample text. Visit http://www.mydomain.com/help.php for more help. Visit http://www.mydomain.com/contact.php if you wish to contact us."; 

$str2 = preg_replace('~(http://www.mydomain.com/)([^ ]+?)\.php~i', '\1mypage.php?url=\2.php', $str); 

// $str: 
// This is a sample text. Visit: http://www.microsoft.com/help.asp Sample text. Please visit http://www.mydomain.com/sometime.jpg. This is some random text. And this is some random sample text. Visit http://www.mydomain.com/mypage.php?url=help.php for more help. Visit http://www.mydomain.com/mypage.php?url=contact.php if you wish to contact us. 

(編輯:校正後的輸出)

+0

太棒了!像魅力一樣工作!非常感謝。 – Devner 2011-03-06 15:11:09

+0

@Devner,不客氣;) – Czechnology 2011-03-06 18:31:15

0
(?:http:\/\/)?(?<domain>(?:www\.)?mydomain\.com)(?<path>(?:[^:s:]*?)\/)(?<filename>[^:s:]*?)\.php(?:\??) 

域 - www.mydomain.com

路徑 -/

文件名 - 幫助

任何域

(?:http:\/\/)?(?<domain>[^:s:\/]*)(?<path>(?:[^:s:]*?)\/)(?<filename>[^:s:]*?)\.php(?:\??) 
+0

感謝您的答覆。但是我很困惑如何使用它。任何幫助? – Devner 2011-03-06 15:11:50