2012-02-01 47 views
0

我有以下的,簡單的代碼:str_replace函數不更換正確

$text = str_replace($f,'<a href="'.$f.'" target="_blank">'.$u.'</a>',$text); 

其中$ f是一個URL,如http://google.ca,和$ u是URL的名稱(我的功能將其命名爲「谷歌」) 。

我的問題是,是,如果我給我的函數的字符串像

http://google.ca http://google.ca 

返回

<a href="<a href="http://google.ca" target="_blank">Google</a>" target="_blank">Google</a> <a href="<a href="http://google.ca" target="_blank">Google</a>" target="_blank">Google</a> 

這顯然不是我想要的。我希望我的函數能夠回顯兩個單獨的可點擊鏈接。但str_replace正在替換第一次出現(它在循環中遍歷所有找到的URL),並且第一次出現已被替換。

我該如何告訴str_replace忽略那個特定的,然後轉到下一個?給出的字符串是用戶輸入,所以我不能只給它一個靜態偏移或任何與substr,我已經嘗試過。

謝謝!

+6

這並不是說'str_replace'被替換不正確的,它只是你」重新使用它。 (肛門,但是真的。):-) – 2012-02-01 20:25:45

+0

是的,我知道。我想知道是否有其他方法可以正常工作。 – Scott 2012-02-01 20:30:02

回答

1

的一種方式,但它是一個有點雜牌的:你可以使用臨時標誌物(希望)將不會出現在字符串中

$text = str_replace ($f, '<a href="XYZZYPLUGH" target="_blank">' . $u . '</a>', 
        $text); 

這樣一來,第一次換人也不會再次發現。那麼,在年底(你處理整個行之後),只需更改標記回:

$text = str_replace ('XYZZYPLUGH', $f, $text); 
+0

這似乎是工作,謝謝! – Scott 2012-02-01 20:44:28

0

爲什麼不通過你的網址功能的陣列,而不是?

function makeLinks(array $urls) { 
    $links = array(); 

    foreach ($urls as $url) { 
     list($desc, $href) = $url; 
     // If $href is based on user input, watch out for "javascript: foo;" and other XSS attacks here. 
     $links[] = '<a href="' . htmlentities($href) . '" target="_blank">' 
       . htmlentities($desc) 
       . '</a>'; 
    } 

    return $links; // or implode('', $links) if you want a string instead 
} 

$urls = array(
    array('Google', 'http://google.ca'), 
    array('Google', 'http://google.ca') 
); 

var_dump(makeLinks($urls)); 
+0

這基本上是我現在正在做的。循環遍歷每個已找到的「URL」並將其轉換爲鏈接的foreach循環。 – Scott 2012-02-01 20:39:36

0

如果我正確理解你的問題,你可以使用函數sprintf。我認爲這樣的事情應該有效:

function urlize($name, $url) 
{ 
    // Make sure the url is formatted ok 
    if (!filter_var($url, FILTER_VALIDATE_URL)) 
     return ''; 

    $name = htmlspecialchars($name, ENT_QUOTES); 
    $url = htmlspecialchars($url, ENT_QUOTES); 

    return sprintf('<a href="%s">%s</a>', $url, $name); 
} 

echo urlize('my name', 'http://www.domain.com'); 
// <a href="http://www.domain.com">my name</a> 

我還沒有測試它。

0

我建議你使用的preg_replace而不str_replace函數在這裏這樣的代碼:

$f = 'http://google.ca'; 
$u = 'Google'; 
$text='http://google.ca http://google.ca'; 
$regex = '~(?<!<a href=")' . preg_quote($f) . '~'; // negative lookbehind 
$text = preg_replace($regex, '<a href="'.$f.'" target="_blank">'.$u.'</a>', $text); 
echo $text . "\n"; 
$text = preg_replace($regex, '<a href="'.$f.'" target="_blank">'.$u.'</a>', $text); 
echo $text . "\n"; 

OUTPUT:

<a href="http://google.ca" target="_blank">Google</a> <a href="http://google.ca" target="_blank">Google</a> 
<a href="http://google.ca" target="_blank">Google</a> <a href="http://google.ca" target="_blank">Google</a>