Replace Markdown-like links with HTML links in a string

后端 未结 2 503
[愿得一人]
[愿得一人] 2020-12-22 13:16

I have a strings of the form

\"Look at this [website]{http://www.stackoverflow.com} 
or at this [page]{http://www.google.com}\"

and I want

相关标签:
2条回答
  • 2020-12-22 14:01

    This can be made easily by using preg_replace:

    $pattern = "/(\\[([^\\]]+)\\]\\{([^\\}]+)\\})/";
    $replacement = '<a href="$3">$2</a>';
    $finalStr = preg_replace($pattern, $replacement, $yourString);
    
    0 讨论(0)
  • 2020-12-22 14:13

    try it with preg_replace

    $str="Look at this [website]{http://www.stackoverflow.com} or at this [page]{http://www.google.com}";
    
    echo preg_replace('/\[(.*?)\]\{(.*?)\}/', "<a href='$2'>$1</a>", $str);
    

    output:

    Look at this <a href='http://www.stackoverflow.com'>website</a> or at this <a href='http://www.google.com'>page</a>
    

    working Example: https://3v4l.org/jLbff

    0 讨论(0)
提交回复
热议问题