Answers for "php + regex"

PHP
-2

regex php

ive never used regex expressions till now and had loads of difficulty trying to convert a [url]link here[/url] into an href for use with posting messages on a forum, heres what i manage to come up with:

$patterns = array(
            "/[link](.*?)[/link]/",
            "/[url](.*?)[/url]/",
            "/[img](.*?)[/img]/",
            "/[b](.*?)[/b]/",
            "/[u](.*?)[/u]/",
            "/[i](.*?)[/i]/"
        );
        $replacements = array(
            "<a href="\1">\1</a>",
            "<a href="\1">\1</a>",
            "<img src="\1">",
            "<b>\1</b>",
            "<u>\1</u>",
            "<i>\1</i>"
            
        );
        $newText = preg_replace($patterns,$replacements, $text);

at first it would collect ALL the tags into one link/bold/whatever, until i added the "?" i still dont fully understand it... but it works :)
Posted by: Guest on August-13-2021

Browse Popular Code Answers by Language