0

I have long struggled with programming languages ​​such as PHP, Javascript, HTML, etc. But my weakness is still very disturbing is about regex.

Previously I felt comfortable without understanding it but now I find the point where I have to use a regex function.

I want to replace a html tag that is created from a rich text editor, say [RTE] so that when I type [code] in the box and then I hit enter it will be translated by RTE <div>[code]</div>

What I need is to change the <div>[code]</div> into an opening html tag <div class="code">

I have tried using str_replace() PHP function as bellow :

$content = str_replace(
               '<div>[code]</div>',
               '<div class="code">',
               $_POST['content']
           );

but it's not work, I think maybe I need to use preg_replace() function but I can't. Can someone help me what type the sample code to do that?

kefy
  • 535
  • 2
  • 10

1 Answers1

0

In preg_replace() function, you need to escape [,] symbols, so that it would match the literal [,] symbols.

Regex:

<(div)>\[([^\]]*)\]<\/\1>

REplacement string:

<\1 class="\2">

DEMO

Avinash Raj
  • 172,303
  • 28
  • 230
  • 274