Reputation: 33
I want to give users some formatting options like Reddit or stackOverFlow do, but want to keep it in PHP. How can parse a string in PHP such that it recognizes patterns like **[anything here]**
?
explode() doesn't seem to solve the problem as elegantly as I'd like. Should I just use nested ifs and fors based on explode()'s output? Is there a better solution here?
Upvotes: 0
Views: 70
Reputation: 836
Check regular expressions:
$string = '*bold* or _underscored_ or even /italic/ ..';
// italic
$string = preg_replace('~/([^/]+)/~', '<i>$1</i>', $string);
// bold
$string = preg_replace('/\*([^\*]+)\*/', '<b>$1</b>', $string);
// underscore
$string = preg_replace('/_([^_]+)_/', '<u>$1</u>', $string);
echo $string;
output:
<b>bold</b> or <u>underscored</u> or even <i>italic</i> ..
or use a BBCode parser.
Upvotes: -1
Reputation: 13257
This has already been done countless times by others, I'd recommend using existing libraries. For example, you can use Markdown: http://michelf.com/projects/php-markdown/
Upvotes: 2