![](/img/trans.png)
[英]Find Variable occurrences of %string in document and replace with suffix. %string .prefix but not href when found as part of a Url
[英]Find URL in string, replace it and alter href
我目前有一些數據庫條目,如下所示:
1. This is some text http://www.sitehere.com more text
2. Text https://www.anothersite.com text text text
3. http://sitehere.com http://sitehereagain.com
4. Just text here blabla
我正在嘗試在打印它們時過濾這些條目,並在所有URL中添加http://anothersite.com/?
。 還要將新的URL目標作為鏈接,但將原始URL保留為文本:
text text <a href="http://anothersite.com/?http://sitehere.com">http://sitehere.com</a> text
到目前為止,我已經成功添加了http://anothersite.com/?
部分具有以下代碼:
$result = preg_replace('/\bhttp:\/\/\b/i', 'http://anothersite.com/?http://', $input);
$result = preg_replace('/\bhttps:\/\/\b/i', 'http://anothersite.com/?https://', $input);
但是ahref不是我想要的方式。 相反,它是:
text text <a href="http://anothersite.com/?http://sitehere.com">http://anothersite.com/?http://sitehere.com</a> text
PS:我不是在尋找JavaScript解決方案:)謝謝!
下面的代碼應該工作。 我做了一些大的更改。 第一個是我使用的是preg_replace_callback
而不是preg_replace
因此我可以正確地編碼URL並更好地控制輸出。 另一個變化是我匹配整個域,因此回調函數可以在<a>
標記之間插入URL,也可以將其添加到超鏈接中。
<?php
$strings = array(
'This is some text http://www.sitehere.com more text',
'Text https://www.anothersite.com text text text',
'http://sitehere.com http://sitehereagain.com',
'Just text here blabla'
);
foreach($strings as $string) {
echo preg_replace_callback("/\b(http(s)?:\/\/[^\s]+)\b/i","updateURL",$string);
echo "\n\n";
}
function updateURL($matches) {
$url = "http://anothersite.com/?url=";
return '<a href="'.$url.urlencode($matches[1]).'">'.$matches[1].'</a>';
}
?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.