-->

How to make PHP BB Codes with RegExp?

2019-09-24 18:10发布

问题:

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!

回答1:

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.



回答2:

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 the preg_replace() function.