user5137907
user5137907

Reputation:

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 ?

Upvotes: 2

Views: 109

Answers (1)

Rizier123
Rizier123

Reputation: 59691

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

$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

Upvotes: 3

Related Questions