2012-02-16 91 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