PHP正则表达式 - 用链接替换多个标签之间的文本

时间:2017-03-12 22:15:10

标签: php regex

我有一个看起来像这样的字符串

A <<double>> <<tripod>> (for holding a <<plate>>, etc.) with six feet, of which three rest on the ground, in whatever position it is placed.

如何以&lt;&lt;&lt;&lt; &GT;&GT;成为一个链接。

结果应如下所示:

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.

1 个答案:

答案 0 :(得分:1)

这样的事情应该有效:

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