Reputation: 23
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.
Upvotes: 0
Views: 52
Reputation: 2156
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);
Upvotes: 1