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

Link to comment
Share on other sites

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

Link to comment
Share on other sites

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])
?>

Link to comment
Share on other sites

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;
?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.