Search code examples
latexbracketspreg-replace-callback

preg_replace change brackets and text


I have a text string in PHP:

$str = 'This is a simple \^{text}. It does not look well \_{styled}.';

What I want to do is to change the "\^{text}" and "_{styled}" using preg_replace to get html code like this

$str = 'This is a simple <sup>text<sup>. It does not look well <sub>styled</sub>.';

What I have done now is this:

function Translate($str)
{
   return preg_replace('/\\\\\^\{.*\}/i', '<sup>$1</sup>', $str);
}
echo Translate("this offer starts at \^{abc}");

This does not work properly with $1! In $0 the entire match is correct... Is there someone who can help me with that? Regars!


Solution

  • Solution: Quick and dirty: $str = 'This is a simple \^{text}. It does not look well _{styled}.'; echo preg_replace('~(\\\^{)(.?)(})~', '$2', $str); echo preg_replace('~(\\_{)(.?)(})~', '$2', $str); Maybe someone has a better solution?