2016-05-26 58 views
0

我有一個已經從一個函數返回以下HTML:輸出HTML與preg_replace_callback不是爲了

<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,如果是的話如何?

+0

你的代碼沒有問題:https://3v4l.org/4PhnA你嘗試'回聲__t($比賽[1]);' – Akam

+0

@Akam我不能'echo'的'__t ($匹配[1])'。他們必須與其餘的html相呼應。爲什麼會發生這種情況?我認爲這是因爲'__t()'函數迴應了字符串而沒有返回它。我怎樣才能防止這一點?我不能編輯'__t()'函數。 – otinanai

+0

@Akam使用't()'函數檢查示例代碼並且不返回字符串:https://3v4l.org/HoprL – otinanai

回答

2

使用輸出緩衝功能。

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(); 
}