2013-08-19 32 views
1

我試圖找到雙引號內的所有東西,並用它使用鏈接替換它。我有超過500行的問題,所以我不想親自去做。使用正則表達式(或任何其他)做高級查找和替換

原始PHP文檔片段:

$q2 = array ("What does Mars look like from Earth?", 
"What is Mars's position relative to Earth?"); 

$q3 = array ("What does Mars's surface look like?", 
"Show me a view of the surface of Mars.", 
"Show me a picture of the surface of Mars."); 

格式化我想:

$q2 = array ("<a href="answer.php?query=What+does+Mars+look+like+from+Earth%3F">What does Mars look like from Earth?</a>", 
<a href="answer.php?query=What+is+Mars's+position+relative+to+Earth%3F">"What is Mars's position relative to Earth?"); 

我嘗試使用正則表達式,但沒有任何與它以前的經驗,我是不成功的。使用RegExr(my example)我想出了一個發現:「[A-Za-z0-9 \ s。\?'] *」和替換:< a href = answer.php?query = $ &> $ &「

這只是給出的結果就像

$q2 = array (<a href=answer.php?query="What does Mars look like from Earth?">"What does Mars look like from Earth?"</a>", 

這是接近,但不是我所需要的。希望有人知道什麼代替我應該使用,或更好的方案去嘗試。任何幫助,將不勝感激。

+1

爲什麼不只是建立你從數組需要動態數組?如果您不需要擔心編寫HTML,對URL進行正確的URL編碼等等,那麼更新數組值會容易得多。只需編寫一個函數,通過它可以傳遞您的數組問題並接收數組的鏈接。順便說一句,你應該引用你的'href'值是你想要格式正確的HTML。 –

+0

也許你可以嘗試使用空格作爲分隔符分割?並把每個拆分數組放回到一個字符串。 –

+0

我不知道這意味着什麼,但我有任何建議。我不需要使用正則表達式,它只是一個想法。 – Alex

回答

1

爲什麼不只是做一個這樣的函數,你可以傳遞你的數組並獲取返回的鏈接數組?

function make_questions_into_links($array) { 
    if (!is_array($array)) { 
     throw new Exception('You did not pass an array') 
    } else if (empty($array)) { 
     throw new Exception('You passed an empty array'); 
    } 

    return array_map(function($element) { 
     return '<a href="answer.php?query=' . urlencode($element) . '">' . $element . '</a>'; 
    }, $array); 
} 
+0

這工作。謝謝 – Alex

0

我會通過下面的函數來運行它們,而不是用正則表達式更新源代碼。

function updateQuestions(&$questions){ 
    foreach($questions as $key => $value){ 
     $questions[$key] = '<a href="answer.php?query=' . urlencode($value) . '">' . $value . '</a>'; 
    } 
} 

updateQuestions($q2); 
+0

讓我嘗試一下,如果它有效,我會盡快回復你們。謝謝 – Alex

+0

我收到第二行的語法錯誤。 (我試圖把它放在一個PHP文件,並通過它運行) – Alex

+0

我錯過了'$' – cmorrissey

0

下面的代碼應該工作:

$q2 = array ('"What does Mars look like from Earth?"', 
      '"What is Mars\'s position relative to Earth?"' 
      ); 
$aq2 = preg_replace_callback(array_fill(0, count($q2), '/(?<!href=)"([^"]+)"/'), 
     function($m){return '<a href="answer.php?query='.urlencode($m[1]).'">'.$m[1].'</a>';}, 
     $q2); 

// test the output 
print_r($aq2); 

OUTPUT:

Array 
(
    [0] => <a href="answer.php?query=What+does+Mars+look+like+from+Earth%3F">What does Mars look like from Earth?</a> 
    [1] => <a href="answer.php?query=What+is+Mars%27s+position+relative+to+Earth%3F">What is Mars's position relative to Earth?</a> 
)