2012-02-16 94 views
0

我有一個鍵和一箇中/長字符串的數組。 我只需要用鏈接包含的相同鍵來替換我在本文中找到的最大2個鍵。 謝謝。PHP替換字符串中的鍵

例:

$aKeys = array(); 
$aKeys[] = "beautiful"; 
$aKeys[] = "text"; 
$aKeys[] = "awesome"; 
... 

$aLink = array(); 
$aLink[] = "http://www.domain1.com"; 
$aLink[] = "http://www.domain2.com"; 

$myText = "This is my beautiful awesome text"; 


should became "This is my <a href='http://www.domain1.com'>beautiful</a> awesome <a href='http://www.domain2.com'>text</a>"; 
+1

如何對所有這些變量看起來怎麼樣和你是如何希望他們看起來像一些具體的代碼? – 2012-02-16 09:39:46

回答

0

所以,你可以使用一個片段是這樣的。我建議你通過使用乾淨的類而不是像global這樣的東西來更新這個代碼 - 只是用它來向你展示如何用更少的代碼解決這個問題。

// 2 is the number of allowed replacements 
echo preg_replace_callback('!('.implode('|', $aKeys).')!', 'yourCallbackFunction', $myText, 2); 

function yourCallbackFunction ($matches) 
{ 
    // Get the link array defined outside of this function (NOT recommended) 
    global $aLink; 

    // Buffer the url 
    $url = $aLink[0]; 

    // Do this to reset the indexes of your aray 
    unset($aLink[0]); 
    $aLink = array_merge($aLink); 

    // Do the replace 
    return '<a href="'.$url.'">'.$matches[1].'</a>';  
} 
1

不真正瞭解你所需要的,但你可以這樣做:

$aText = explode(" ", $myText); 
$iUsedDomain = 0; 
foreach($aText as $sWord){  
    if(in_array($sWord, $aKeys) and $iUsedDomain < 2){ 
     echo "<a href='".$aLink[$iUsedDomain++]."'>".$sWord."</a> "; 
    } 
    else{ echo $sWord." "; } 
} 
+0

它的工作原理,謝謝 – 2012-02-16 10:28:53