Forum Moderators: coopster
$string = preg_replace('/\[b\](.*)\[\/b\]/', '<strong>$1</strong>', $string);
This can be a little more efficient, and also .* means "zero or more of any character" so it will slurp up the [/b]. What you want is one or more of any character NOT a [ as below. Added case-insensitive, global, and multiline modifers . . .
$tags = Array (
'b' => 'strong',
'i' => 'em',
'bullet list' => 'ul',
'ordered list' => 'ol',
'list item' => 'li'
);
(or, if all the same, b=b, i=i, a simple list array.)
foreach ($tags as $key=>$value) {
$content = preg_replace('/\[$key\]([^\[]+)\[\/$key\]/img', "<$value>$1<\/$value>", $content);
}
This should also work for lists. The multiline modifier means treat the regex as multiple lines, the global means perform the replacement globally (may not be supported by PHP, or inherently global, if it dies on you remove the g.)
When in doubt, analyze your regexp character by character:
\[$key\] Begins with [$key]
( Begin storing the result in $1
[^\[]+ Followed by one or more of any character NOT a [
) end saving of the pattern in $1
\[\/$key\] ends with [/$key]
img case insensitive, treat as multiple lines, apply regex globally
[edited by: rocknbil at 5:44 pm (utc) on July 26, 2009]