我有一個功能,將在鏈接之前添加<a href>
標記,鏈接之後添加</a>
。但是,對於某些網頁而言,它會中斷。你將如何改進這個功能?謝謝!PHP - 將鏈接添加到字符串中的URL
function processString($s)
{
// check if there is a link
if(preg_match("/http:\/\//",$s))
{
print preg_match("/http:\/\//",$s);
$startUrl = stripos($s,"http://");
// if the link is in between text
if(stripos($s," ",$startUrl)){
$endUrl = stripos($s," ",$startUrl);
}
// if link is at the end of string
else {$endUrl = strlen($s);}
$beforeUrl = substr($s,0,$startUrl);
$url = substr($s,$startUrl,$endUrl-$startUrl);
$afterUrl = substr($s,$endUrl);
$newString = $beforeUrl."<a href=\"$url\">".$url."</a>".$afterUrl;
return $newString;
}
return $s;
}
正則表達式是有點草率,但我投入的99%,將有正確的網址,如果有的話 – AlexBrand 2010-11-18 16:53:15
它打破什麼網頁? – 2010-11-18 16:54:15
開始時你也會測試https,但稍後會忽略「s」。不知道,如果這導致這個錯誤,因爲我也不知道,哪些頁面被破壞;) – KingCrunch 2010-11-18 16:58:39