开发者

PHP: Find and replace clickable (.php) links with custom info

I want to be able to find and replace all clickable links in a piece of text with some custom information. Please consider the following example:

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.

In the above text, I want to be able to replace all clickable ".php" links to something like below:

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/m开发者_Go百科ypage.php?url=help.php for more help. Visit http://www.mydomain.com/mypage.php?url=contact.php if you wish to contact us.

I tried using preg_replace and ereg_replace but it did not work for me.

All help is appreciated. Thank you.


It is only on your domain?

$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.

(edit: corrected the output)


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

domain - www.mydomain.com

path - /

filename - help

for any domain

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜