Basically, I will first analyze the lang section, for example:
<French>Chat</French><English>Cat</English>
with this:
"@(<($defLangs)>.*?</\\2>) +@i "
Then parse the right line with the callback.
If you got php 5.3+, then:
function transLang($str, $lang, $defLangs = 'French|English') { return preg_replace_callback ( "@(<($defLangs)>.*?</\\2>) +@i ", function ($matches) use($lang) { preg_match ( "/<$lang>(.*?)<\/$lang>/i", $matches [0], $longSec ); return $longSec [1]; }, $str ); } echo transLang ( $str, 'French' ), "\n", transLang ( $str, 'English' );
If not, a little harder:
class LangHelper { private $lang; function __construct($lang) { $this->lang = $lang; } public function callback($matches) { $lang = $this->lang; preg_match ( "/<$lang>(.*?)<\/$lang>/i", $matches [0], $subMatches ); return $subMatches [1]; } } function transLang($str, $lang, $defLangs = 'French|English') { $langHelper = new LangHelper ( $lang ); return preg_replace_callback ( "@(<($defLangs)>.*?</\\2>) +@i ", array ( $langHelper, 'callback' ), $str ); } echo transLang ( $str, 'French' ), "\n", transLang ( $str, 'English' );
Andrew
source share