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

どのようにいくつかの具体的なコードについてのすべてのこれらの変数がどのように見えるかについて、あなたは彼らが見えるようにする方法は? –

答えて

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

作品、ありがとう –