Search code examples
phpregexcapture-group

Regex capture groups in PHP


I'm a bit out of my depth here, but I'm trying to let users write links, not entirely unlike how StackOverflow formats links.

Ideally, when a user enters [text to link here][23] in a text area, they will end up with <a href="path/to/img/id/23">text to link here</a> when that information is written from the database to the page.

My part I'm failing is how to extract text to link and 23 from the matched pattern

This is the pattern I'm using, but a preg_replace using this will only allow me to replace the entire string, not operate on it. I might be mistaken in my use of preg_replace.


Solution

  • You can operate with preg_replace_callback, but even that is unnecessary:

    preg_replace('/\[(.+?)\]\[(\d+)?\]/', '<a href="path/to/img/id/\2">\1</a>', $st);