1

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.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Jitu
  • 57
  • 7
  • This should help: https://stackoverflow.com/questions/206059/php-validation-regex-for-url – dale landry Apr 07 '20 at 04:18
  • Does this answer your question? [PHP validation/regex for URL](https://stackoverflow.com/questions/206059/php-validation-regex-for-url) – dale landry Apr 07 '20 at 04:19
  • Use the capturing groups in the replacement https://regex101.com/r/riLKnf/1 You could also use negated character classes instead `\[{2}([^][|]*)\|([^][]*)\]{2}` https://regex101.com/r/qvY503/1 – The fourth bird Apr 07 '20 at 06:51

1 Answers1

1

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>
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563