How to make PHP BB Codes with RegExp?

无人久伴 提交于 2019-12-13 09:08:28

问题


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.



来源:https://stackoverflow.com/questions/10458103/how-to-make-php-bb-codes-with-regexp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!