regex - How to make PHP BB Codes with RegExp?

403

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!

592

Answer

Solution:

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);
    printf("\n");
}

Output:

D: Before [url]http://www.stackoverflow.com[/url] after
C: Before <a href="http://www.stackoverflow.com">http://www.stackoverflow.com</a> after

D: Before [url]http://www.stackoverflow.com[/url] [url]http://www.google.com[/url] after
C: Before <a href="http://www.stackoverflow.com">http://www.stackoverflow.com</a> <a href="http://www.google.com">http://www.google.com</a> after

D: Before [url=http://www.stackoverflow.com]StackOverflow[/url]
C: Before <a href="http://www.stackoverflow.com">StackOverflow</a>

D: Before [img]https://www.google.com/logos/2012/haring-12-hp.png[/img] after
C: Before <img src="https://www.google.com/logos/2012/haring-12-hp.png" /> 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.

568

Answer

Solution:

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

$input = "[link=http://www.google.com]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

Source

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.