使用正则表达式(或任何东西)进行高级查找和替换

时间:2013-08-19 16:29:39

标签: php regex arrays replace

我正在尝试在双引号内找到所有内容并将其替换为使用它的链接。我有500多行问题,所以我不想手工完成。

原始php doc片段:

$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。\?'] *”和替换:&lt; a href = answer.php?query = $&amp;&gt; $&amp;“

这只是给出了像

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

这很接近,但不是我需要的。希望有人知道我应该使用什么替换,或者尝试更好的程序。任何帮助将不胜感激。

3 个答案:

答案 0 :(得分: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);
}

答案 1 :(得分:0)

我会通过下面的函数来运行它们。而不是使用正则表达式更新源代码。

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

updateQuestions($q2);

答案 2 :(得分: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);

<强>输出:

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>
)