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.

2
  • Don't parse HTML with regex: stackoverflow.com/questions/1732348/… (see the first answer to that question) Commented Mar 4, 2012 at 2: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. Commented Mar 4, 2012 at 2:34

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Yeah your right I forgot about the whole greedyness thing. Thanks I didn't know about this function.
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);

5 Comments

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.
Good point Platinum Azure. Also thanks Qtax for the information.
@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: Shane Larson never said where the HTML was coming from. On a forum that supports a <code> tag, the input is highly relevant.
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.