1

My website blew up recently because the eregi_replace got phased out. Now I need to convert them into a preg_replace or something else. This worked with most of my functions but I'm having trouble with the ones that simulate bbtags.

Could someone help?

$txt = eregi_replace("\\[url\\]([^\\[]*)\\[/url\\]", "<a href=\"\\1\" target=\"_blank\">\\1</a>", $txt);
$txt = eregi_replace("\\[img\\]([^\\[]*)\\[/img\\]", "<a href=\"\\1\"><img src=\"\\1\" width=\"150px\" height=\"150px\" style=\"float: left; margin-right: 10px;\" /></a>", $txt);
$txt = eregi_replace("\\[cimg\\]([^\\[]*)\\[/cimg\\]", "<a href=\"\\1\"><img src=\"\\1\" width=\"100px\" height=\"100px\" /></a>", $txt);
$txt = eregi_replace("\\[code\\]([^\\[]*)\\[/code\\]", "<br><br><strong>Code:</strong><table width=\"80%\" border=\"0\" cellpadding=\"3\" cellspacing=\"0\" bgcolor=\"#FFFFFF\" style=\"border:1px solid gray;\"><tr><td bgcolor=\"#FFFFFF\"><font color=\"#009900\" size=\"-2\">\\1</font></td></tr></table><br>", $txt);
Coolcrab
  • 2,655
  • 9
  • 39
  • 59
  • Replacing `*` with `*?` (plus all the other "mechanical" stuff you have done to the other regexes) should fix things. – Jon Jun 29 '13 at 13:46
  • @Jon: you don't need to replace `*` by `*?` since the character class doesn't contain opening square brackets. – Casimir et Hippolyte Jun 29 '13 at 13:53
  • @CasimiretHippolyte: Right, I didn't read the regex carefully just remembered that default greediness differs between the two flavors. But I 'm not sure why straight `preg_replace` would not work then. – Jon Jun 29 '13 at 13:57

1 Answers1

1

For example:

$txt = preg_replace('~\[url]([^[]*+)\[/url]~i', '<a href="$1" target="_blank">$1</a>', $txt);

*+ means zero or more times (possessive)

Notice: You don't need to escape closing square brackets. You don't need to escape an opening square bracket in a character class. Using simple quotes to surround your string is the best choice here since you don't have to escape double quotes inside.

The interest of using \[^]] instead of the dot is that you can avoid the lazy quantifier .*? and obtain a more performant pattern. The second interest is that you avoid the dotall problem, since this character class matches newlines.

Casimir et Hippolyte
  • 88,009
  • 5
  • 94
  • 125