Q:

Replace specific character only between  and  in PHP

I have something like <code>  <1>  <2>  </code> and I would like to get this : <code>  &lt;1&gt;  &lt;2&gt;  </code> but I want to apply this only inside the <code></code> tags and not anywhere else. 
I already have this : 
$txt = $this->input->post('field');
$patterns = array(
    "other stuff to find", "/<code>.*(<).*<\/code>/m"
);
$replacements = array(
    "other stuff to replace", "&lt;"
);

$records = preg_replace($patterns,$replacements, $txt);

It replaces successfully the character but it removes the surrounded <code></code> tags
Any help will be very appreciated !  Thanks

A:

Other possibility, using callback function:
<? php
$test = "<code> <1> <2></code> some other text <code> other code <1> <2></code>";
$text = preg_replace_callback("#<code>(.*?)</code>#s",'replaceInCode',$test);
echo htmlspecialchars($test. "<br />".$text);

function replaceInCode($row){
    $replace = array('<' => '&lt','>' => '&gt');
    $text=str_replace(array_keys($replace),array_values($replace),$row[1]);
    return "<code>$text</code>";
}

It is not easy (not sure if even possible) to accomplish that without second function, as there can be multiple < symbols inside  block. 
Read more here:
http://php.net/preg_replace_callback

