0

I have string who look like this

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

How can I replace it in format that everything between << >> become a link.

Result should look like this:

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 Answer 1

1

Something like this should work:

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

Another alternative is to use preg_replace_callback and create a recursive function:

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.