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(我的示例)我找到了:“[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>",

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

4

3 回答 3

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);
}
于 2013-08-19T16:43:54.863 回答
0

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

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

updateQuestions($q2);
于 2013-08-19T16:42:18.570 回答
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>
)
于 2013-08-19T16:57:52.173 回答