phphyperlinkpreg-replaceplaceholdersquare-bracket

Convert pairs of square brace placeholders into an HTML hyperlink


I have to do the following with preg_replace() in PHP:

[some text][id] should be replaced by <a href='id'>some_text</a> where id is an integer

Tried the following, unfortunately didn't work as expected:

preg_replace("/\[[^)]\]\[[0-9]+\]/", "<a href='$2'>$1</a>", $string);

Also, an example [some text]][id] with extra bracket may be considered, where the last bracket should be taken.


Solution

  • Here's a solution:

    $string = '[some text][117]';
    $s = preg_replace("/\[([^\]]+)\]\[([0-9]+)\]/","<a href='$2'>$1</a>",$string);
    var_dump($s);
    

    First - to use $1 (or $2) you need to capture pattern in brackets ().

    Second mistake - you're trying to find ^), but you don't have ) in your text. So I replaced ) to ].

    Update for an extra ]:

    $s = preg_replace("/\[([^\]]+)(\]?)\]\[([0-9]+)\]/","<a href='$3'>$1$2</a>",$string);
    

    Not sure what you need to do with this founded ], so I added it to a link text.

    In case of a lot of ]]] you can use:

    $s = preg_replace("/\[([^\]]+)(\]*)\]\[([0-9]+)\]/","<a href='$3'>$1$2</a>",$string);