I’m trying to find the most beautiful way to replace tags in string with <a href="">
.
String: Text text text %link% text
%link% might me any text between %.
URL: https://link.link
Result: Text text text a <href="">
link</a>
text
Please help me to find the best way to do it.
Thanks!
My solution (maybe the weirdest one):
$result = str_rreplace("%", "<a href="" . $url . "">", str_rreplace("%", "</a>", $string));
function str_rreplace($search, $replace, $subject) {
$pos = strrpos($subject, $search);
if ($pos !== false) {
return substr_replace($subject, $replace, $pos, strlen($search));
}
return $subject;
}
2
Answers
May be a simpler way would be:
str_replace()
searches for the%link%
in the $string and replaces it with the<a href="">link</a>
tag. The $url is concatenated within the replacement string to form the complete anchor tag.This would output:
Text text text <a href="https://link.link">link</a> text
This approach is more straight forward and doesn’t require defining an additional function.
Edit:
if you want to replace any text enclosed by
%...%
with a link, you can use regex withpreg__replace_callback()
function. So:You can just use
preg_replace
, with a regex%([^%]+)%
to capture any text between%
in group 1 and then replace that with an anchor:Output