skip to Main Content

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


  1. May be a simpler way would be:

    $string = "Text text text %link% text";
    $url = "https://link.link";
    $result = str_replace("%link%", "<a href="" . $url . "">link</a>", $string);
    

    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 with preg__replace_callback() function. So:

    $string = "Text text text %link% text";
    $url = "https://link.link";
    
    $result = preg_replace_callback('/%(.*?)%/', function($matches) use ($url) {
        return "<a href="" . $url . "">" . $matches[1] . "</a>";
    }, $string);
    
    Login or Signup to reply.
  2. You can just use preg_replace, with a regex %([^%]+)% to capture any text between % in group 1 and then replace that with an anchor:

    $string = "Text text text %link% text";
    $url = "https://link.link";
    
    echo preg_replace('/%([^%]+)%/', "<a href="$url">$1</a>", $string);
    

    Output

    Text text text <a href="https://link.link">link</a> text
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search