'Linkify with provided text in PHP

I'm personally not very good with preg_replace, and could use some help if possible.

I'd like to linkify a string and allow an optional text parameter. Examples:

Input: [[http://www.example.com/path/to/file.ext]]

Output: <a href="http://www.example.com/path/to/file.ext">http://www.example.com/path/to/file.ext</a>


Input: [[http://www.example.com/path/to/file.ext "click here"]]

Output: <a href="http://www.example.com/path/to/file.ext">click here</a>

How would I be able to do this (using preg_replace if possible)?

Thank you in advance.



Solution 1:[1]

Try this regx, you want to match the [[stuff]], right?

 /\[\[(?P<link>[^\s]+)\s(?P<text>[^\]]+)\]\]/

https://regex101.com/r/pT4bL1/1

Id help you with the links but don't know how you create them. For example using preg_match with the 3rd parameter you would have the parts in [[]] and then could just do

  if( preg_match('/\[\[(?P<link>[^\s]+)\s(?P<text>[^\]]+)\]\]/', '[[http://www.example.com/path/to/file.ext "click here"]]', $match ) ){
      echo '<a href="'.$match['link'].'">'.$match['text'].'</a>';
   }

To explain the regx

  • \[\[ - is just the [[
  • (?P<link>[^\s]+) - (?P<name>..,) is named capture group [^\s]+anything but a space.
  • \s a space
  • (?P<text>[^\]]+) same as above except [^\]]+ anything but ]
  • \]\] - the ending ]]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1