Jump to content


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

Gordon Werner

preg_replace question ...

Recommended Posts

Good morning.


If I want a user to be able to enter simple markup into a text field using [tag]xyz[/tag] format so that I can convert it on display to <tag>xyz</tag> format, how do I formulate the preg_replace expressions?



[b]some text[/b]
[i]some text[/i]
[u]some text[/u]

etc ...


should become:


<b>some text</b>
<i>some text</i>
<u>some text</u>
<a href="http://www.www.com">http://www.www.com</a>
<a href="mailto:someone@somewere.com">someone@somewere.com</a>
<img src="http://www.com/image.jpg" />

etc ...


also if I want the user to be able to enter the following:




and have the display change those tags to the ascii characters ... would str_replace be the best way to handle those? or would preg_replace also work?


Any help would be appreciated as I am trying to learn this stuff and haven't found any good examples that are clear to a beginner.





Share this post

Link to post
Share on other sites

preg_replace will work. It can take in arrays as arguments so you can just put up 2 arrays. First array is the regexp and the second array is the replacement. So for example:


$bb = array(

$replacement = array(

$new_str = preg_replace($bb, $replacement, $str);

Share this post

Link to post
Share on other sites

Here's something I have laying around




$patterns = array(

  //BB Code

  "/ \:\) /",
  "/ \:\( /",
  "/ \ /",
  "/ \ /",
  "/ \:\| /",
  "/ \ /",
  "/ \:\? /",
  "/ \;\) /");

$replacements = array(

  //BB Code
  "<a href=\"\\1\">\\1</a>",
  "<a href=\"\\1\" target=\"_blank\">\\2</a>",
  "<img border=\"0\" src=\"\\1\">",
  "<div><b>Quote:</b> <i>\\1</i></div>",
  "<br /><b>Code:</b><br /><div style=\"overflow:auto;\"><xmp>\\1</xmp></div><br />",
  "<font \\1=\"\\2\">\\3</font>",
  "<br />",

  " <img src=\"smilies/happy.gif\" border=\"0\"> ",
  " <img src=\"smilies/angry.gif\" border=\"0\"> ",
  " <img src=\"smilies/omg.gif\" border=\"0\"> ",
  " <img src=\"smilies/tounge.gif\" border=\"0\"> ",
  " <img src=\"smilies/dry.gif\" border=\"0\"> ",
  " <img src=\"smilies/biggrin.gif\" border=\"0\"> ",
  " <img src=\"smilies/confused.gif\" border=\"0\"> ",
  " <img src=\"smilies/wink.gif\" border=\"0\"> "

$string = "[b]This is bold text[/b] [i]this is italic text[/i] [b][i]This is bold, italic text[/b][/i]";

$result = preg_replace($patterns,$replacements,$string);

echo $result;


Share this post

Link to post
Share on other sites

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