我有看起来像这样的字符串
A <<double>> <<tripod>> (for holding a <<plate>>, etc.) with six feet, of which three rest on the ground, in whatever position it is placed.
我怎样才能以<<>>之间的所有内容成为链接的格式替换它。
结果应如下所示:
A <a href="search/double">double</a> <a href="search/tripod">tripod</a> (for holding a <a href="search/plate">plate</a>, etc.) with six feet, of which three rest on the ground, in whatever position it is placed.
这样的事情应该工作:
$str = "A <<double>> <<tripod>> (for holding a <<plate>>, etc.) with six feet, of which three rest on the ground, in whatever position it is placed.";
preg_match_all("|<<(.*)>>|U", $str, $out, PREG_PATTERN_ORDER);
for($i=0; $i < count($out[0]); $i++) {
$str = str_replace($out[0][$i], '<a href="search/'. $out[1][$i] .'">'. $out[1][$i] .'</a>', $str);
}
echo $str;
另一种选择是使用preg_replace_callback并创建一个递归函数:
function parseTags($input) {
$regex = "|<<(.*)>>|U";
if (is_array($input)) {
$input = '<a href="search/'.$input[1].'">'.$input[1].'</a>';
}
return preg_replace_callback($regex, 'parseTags', $input);
}
$str = "A <<double>> <<tripod>> (for holding a <<plate>>, etc.) with six feet, of which three rest on the ground, in whatever position it is placed.";
echo parseTags($str);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句