Jump to content

[SOLVED] Basic preg-replace for bbcode


DeanWhitehouse

Recommended Posts

Lol, you centered the text.

 

Like this:

$str = "
[center][b]Bold and centered text![/b][/center]
";

$str = preg_replace("/\[center\](.*?)\[\/center\]/","<center>\\1</center>",$str);
$str = preg_replace("/\[b\](.*?)\[\/b\]/","<b>\\1</b>",$str);

echo $str;

 

Here's a link to basic regular expression help in PHP:

http://www.sitepoint.com/article/regular-expressions-php

ok, last problem, i want to use this on lots of pages , from a forum, to members profiles.

 

how would i do this without writing it on every page , i was think something like

 

function bbcode(code)

{

$str = preg_replace("/\[center\](.*?)\[\/center\]/","<center>\\1</center>",code);

$str = preg_replace("/\[b\](.*?)\[\/b\]/","<b>\\1</b>",code);

}

 

then to call, i would do

bbcode(cake); ?? is that correct

Is this how i call from a function?

 

<?php 
function bbcode(code)
{
$str = preg_replace("/\[center\](.*?)\[\/center\]/","<center>\\1</center>",$str);
$str = preg_replace("/\[b\](.*?)\[\/b\]/","<b>\\1</b>",$str);
$str = preg_replace("/\<center\>(.*?)\<\/center\>/","<center>\\1</center>",$str);
}
echo bbcode([b]cake[/b])
?>

I would use a return inside the function.

 

<?php 
function bbcode(code)
{
$str = preg_replace("/\[center\](.*?)\[\/center\]/","<center>\\1</center>",$str);
$str = preg_replace("/\[b\](.*?)\[\/b\]/","<b>\\1</b>",$str);
$str = preg_replace("/\<center\>(.*?)\<\/center\>/","<center>\\1</center>",$str);

return $str; //return the formatted string
}

$toformat = "
[center]Hello There! [b]How are you today?[/b][/center]
";
$toecho = bbcode($toformat);

echo $toecho;
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.