输出 HTML 与 preg_replace_callback 不按顺序
Output HTML with preg_replace_callback not in order
我从函数返回了以下 HTML:
<fieldset>
<legend>Title</legend>
<div>
<label>
<i>String that gets translated</i>
</label>
<textarea>
<i>Another string</i>
</textarea>
</div>
</fieldset>
然后我使用 preg_replace_callback
获取 <i>
标签之间的字符串,并将其替换为翻译后的字符串,如下所示:
$translation = preg_replace_callback("/\<i\>(.+?)\<\/i\>/", 'translator', $html);
function translator($matches) {
return __t($matches[1]);
}
但是,当我输出 html - echo $translation;
- 我得到以下信息:
String that gets translated Another string<--this is not inside <i> tags
<fieldset>
<legend>Title</legend>
<div>
<label>
<i></i> <--the string should be placed here
</label>
<textarea>
<i></i> <--and here
</textarea>
</div>
</fieldset>
这个问题困扰了我一整天,一直想不出解决的办法。如何以正确的顺序输出 html 和翻译后的字符串?我是否必须使用 DOMDocument::loadHTML
,如果是,如何使用?
使用输出缓冲函数。
ob_flush(); // flush any pending output buffer
ob_start();
$translation = preg_replace_callback("/\<i\>(.+?)\<\/i\>/", 'translator', $html);
ob_end_clean();
function translator($matches) {
__t($matches[1]);
return ob_get_clean();
}
我从函数返回了以下 HTML:
<fieldset>
<legend>Title</legend>
<div>
<label>
<i>String that gets translated</i>
</label>
<textarea>
<i>Another string</i>
</textarea>
</div>
</fieldset>
然后我使用 preg_replace_callback
获取 <i>
标签之间的字符串,并将其替换为翻译后的字符串,如下所示:
$translation = preg_replace_callback("/\<i\>(.+?)\<\/i\>/", 'translator', $html);
function translator($matches) {
return __t($matches[1]);
}
但是,当我输出 html - echo $translation;
- 我得到以下信息:
String that gets translated Another string<--this is not inside <i> tags
<fieldset>
<legend>Title</legend>
<div>
<label>
<i></i> <--the string should be placed here
</label>
<textarea>
<i></i> <--and here
</textarea>
</div>
</fieldset>
这个问题困扰了我一整天,一直想不出解决的办法。如何以正确的顺序输出 html 和翻译后的字符串?我是否必须使用 DOMDocument::loadHTML
,如果是,如何使用?
使用输出缓冲函数。
ob_flush(); // flush any pending output buffer
ob_start();
$translation = preg_replace_callback("/\<i\>(.+?)\<\/i\>/", 'translator', $html);
ob_end_clean();
function translator($matches) {
__t($matches[1]);
return ob_get_clean();
}