我正试图找到双引号中的所有内容,并用它的链接替换它。我有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="answerswer.php?query=What+does+Mars+look+like+from+Earth%3F">What does Mars look like from Earth?</a>",
<a href="answerswer.php?query=What+is+Mars's+position+relative+to+Earth%3F">"What is Mars's position relative to Earth?");
我尝试过使用Regex,但由于之前没有任何使用经验,我没有成功。使用RegExr(我的例子),我找到了:"[a-Za-z0-9''s.''?']*"和替换:<a href=answer.php?查询=$&>$&"
这只是给出了类似的结果
$q2 = array (<a href=answer.php?query="What does Mars look like from Earth?">"What does Mars look like from Earth?"</a>",
这很接近,但不是我需要的。希望有人知道我应该使用什么替代品,或者一个更好的程序来尝试。如有任何帮助,我们将不胜感激。
为什么不制作一个这样的函数,您可以将数组传递给它并返回一个链接数组?
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="answerswer.php?query=' . urlencode($element) . '">' . $element . '</a>';
}, $array);
}
我会通过下面这样的函数来运行它们。而不是用正则表达式更新源代码。
function updateQuestions(&$questions){
foreach($questions as $key => $value){
$questions[$key] = '<a href="answerswer.php?query=' . urlencode($value) . '">' . $value . '</a>';
}
}
updateQuestions($q2);
以下代码应该可以工作:
$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="answerswer.php?query='.urlencode($m[1]).'">'.$m[1].'</a>';},
$q2);
// test the output
print_r($aq2);
输出:
Array
(
[0] => <a href="answerswer.php?query=What+does+Mars+look+like+from+Earth%3F">What does Mars look like from Earth?</a>
[1] => <a href="answerswer.php?query=What+is+Mars%27s+position+relative+to+Earth%3F">What is Mars's position relative to Earth?</a>
)