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.

3

1 Answer 1

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.