简体   繁体   中英

how can I replace [link](#) to <a href=“#”>link</a>?

I want to do something like stackoverflow . actually changing this style []() to this style <a href=""></a> . here is my try:

$str = '[link](#)';
$str = str_replace('[','<a href="',$str);     // output: <a href="link](#)
$str = str_replace(']','">',$str);            // output: <a href="link">(#)
$str = str_replace('(','',$str);              // output: <a href="link">#)
$str = str_replace(')','</a>',$str);          // output: <a href="link">#</a>

but now, I need to change link with # , how can I do that ?

You want to take a look at preg_replace() , with this you can use a regex to replace it, eg

$str = preg_replace("/\[(.*?)\]\((.*?)\)/", "<a href='$2'>$1</a>", $str);

regex explanation:

\[(.*?)\]\((.*?)\)
  • \\[ matches the character [ literally
  • 1st Capturing group (.*?)
    • .*? matches any character (except newline)
      • Quantifier: *? Between zero and unlimited times, as few times as possible, expanding as needed [lazy]
  • \\] matches the character ] literally
  • \\( matches the character ( literally
  • 2nd Capturing group (.*?)
    • .*? matches any character (except newline)
      • Quantifier: *? Between zero and unlimited times, as few times as possible, expanding as needed [lazy]
  • \\) matches the character ) literally

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM