regex - How to make PHP BB Codes with RegExp?


for my website, I want a simple BB code system. Nothing special--just hyperlinks and images will be fine for now.

I'm not good with RegExp. Period. But if someone could show me an example, I may be able to grasp it to clone it into different tags.

Your help is very appreciated!




I have to imagine this exists out there for free somewhere, but here's how I'd do it.

// Patterns
$pat = array();
$pat[] = '/\[url\](.*?)\[\/url\]/';         // URL Type 1
$pat[] = '/\[url=(.*?)\](.*?)\[\/url\]/';   // URL Type 2
$pat[] = '/\[img\](.*?)\[\/img\]/';         // Image
// ... more search patterns here

// Replacements
$rep = array();
$rep[] = '<a href="$1">$1</a>';             // URL Type 1
$rep[] = '<a href="$1">$2</a>';             // URL Type 2
$rep[] = '<img src="$1" />';                // Image
// ... and the corresponding replacement patterns here

// Run tests
foreach($DIRTY as $dirty)
    $clean = preg_replace($pat, $rep, $dirty);

    printf("D: %s\n", $dirty);
    printf("C: %s\n", $clean);


D: Before [url][/url] after
C: Before <a href=""></a> after

D: Before [url][/url] [url][/url] after
C: Before <a href=""></a> <a href=""></a> after

D: Before [url=]StackOverflow[/url]
C: Before <a href="">StackOverflow</a>

D: Before [img][/img] after
C: Before <img src="" /> after

For each$pat pattern element you add, you need to add a$rep element. The$DIRTY array is just a list of test cases and can be any length you think is sufficient.

The important parts here, and the parts that you would use are the$pat and$rep arrays and thepreg_replace() function.




The user asked for something simple, so I gave him something simple.

$input = "[link=]test[/link]";
$replacement = preg_replace('/\[link=(.*?)\](.*?)\[\/link\]/', '<a href="$1">$2</a>', $input);

Where/\[link=(.*?)\](.*?)\[\/link\]/ is the regex,<a href="$1">$2</a> is the format,$input is the input/data, and$replacement is the return.

People are also looking for solutions to the problem: php - laravel remove id if user not login


Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.