Reputation: 67
My string
[[https://example.com|link]]
to convert
<a href="https://example.com>link</a>
My regex is
/\[{2}(.*?)\|(.*?)\]{2}/s
But it's not working.I am new to php regex.
Upvotes: 1
Views: 74
Reputation: 626738
You may use
preg_replace('~\[\[((?:(?!\[\[).)*?)\|(.*?)]]~s', '<a href="$1">$2</a>', $string)
See the regex demo
Details
\[\[
- a [[
substring((?:(?!\[\[).)*?)
- Group 1 ($1
in the replacement pattern refers to the value inside this group): any char (.
), 0 or more occurrences but as few as possible (*?
), that does not start a [[
char sequence ((?!\[\[)
)\|
- a |
char(.*?)
- Group 2 ($2
):]]
- a ]]
substring.See the PHP demo:
$string = "[[some_non-matching_text]] [[https://example.com|link]] [[this is not matching either]] [[http://example2.com|link2]]";
echo preg_replace('~\[\[((?:(?!\[\[).)*?)\|(.*?)]]~s', '<a href="$1">$2</a>', $string);
// => [[some_non-matching_text]] <a href="https://example.com">link</a> [[this is not matching either]] <a href="http://example2.com">link2</a>
Upvotes: 1