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

작동합니다. 감사합니다. –

관련 문제