1
$TOPIC_CONTENT = preg_replace("!<code>(.+)</code>!is","<div style='color: #00FF00;
background-color: #000000; border-radius: 5px; margin: 5px;"<pre>".htmlspecialchars("$0")."</pre></div>",$TOPIC_INFO->content);

How can I get this to work? I have no idea how to pull this off, and I know my current way is invalid.

  • Don't parse HTML with regex: http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags (see the first answer to that question) – Cfreak Mar 04 '12 at 02:29
  • 1
    I'm not parsing it, I'm trying to get the text between the code tags and run htmlspecialchars() on it and create a new div around it. – Shane Larson Mar 04 '12 at 02:34

2 Answers2

3

Use preg_replace_callback. Be a little careful with your regex .. I think you want to use .+? instead of just .+. The usual mantra is "don't parse html with regex," but for something as simple as this I don't see the harm.

Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
2

Except for preg_replace_callback as in tandu's answer, you can also use the /e switch, and your replacement string will be *e*valuated as PHP code, and its result will be used.

I.e you could do:

preg_replace("!<code>(.+?)</code>!ise",
    '"<pre style=\"color: #0f0; background: #000;\">" . htmlspecialchars("$1") . "</pre>"',
    $string);
Qtax
  • 33,241
  • 9
  • 83
  • 121
  • Of course, you absolutely shouldn't use any sort of eval-like functionality if you don't have *absolute control* over both the code being evaluated and the input that might feed into said code. Is `htmlspecialchars` a good enough function to prevent malicious execution? I don't know (not being a PHP expert), and I suggest you don't use this answer until you can be absolutely sure. – Platinum Azure Mar 04 '12 at 02:54
  • Good point Platinum Azure. Also thanks Qtax for the information. – Shane Larson Mar 04 '12 at 02:56
  • @PlatinumAzure, the "input" (that is `$1` in this case) is irrelevant. It can't do any harm no matter what content it has. @Shane, say thanks with the vote button instead. ;-) – Qtax Mar 04 '12 at 03:37
  • @Qtax: Shane Larson never said where the HTML was coming from. On a forum that supports a `` tag, the input is *highly* relevant. – Platinum Azure Mar 04 '12 at 03:52
  • @Platinum, relevant how exactly? Of course the expression will replace whatever part matches with the result of the evaluated string. So what's is your point? You see some problem here except matching "HTML" with regex? In that case tell us what it is. – Qtax Mar 04 '12 at 11:48