Search code examples
phpregexshortcode

PHP Shortcode Regex issue


Hi so I need help in taking a block of html which contains existing shortcode for an old arbitrary system. Taking the code below and and using PHP change so the following :

[CDC](http://www.cdc.gov/)

would be transformed into this :

<a href="http://cdc.gov">CDC</a> 

Any ideas on how i could achive this? There could be multiple instances in one block of code also. If anybody can help , I'd be grateful - thank you!!


Solution

  • The solution using preg_replace function with specific regex pattern:

    $block = "Two excellent websites outlining the major precautions are: [some text](www.cdc.gov) and [who's next](www.who.int) which are the official sites ...";
    
    $block = preg_replace("/\[([^]]+)\]\(([^)]+)\)/", '<a href="$2">$1</a>', $block);
    
    print_r($block);
    

    The output(from source code):

    Two excellent websites outlining the major precautions are: <a href="www.cdc.gov">some text</a> and <a href="www.who.int">who's next</a> which are the official sites ...