0

I have the following HTML that's been returned from a function:

<fieldset>
    <legend>Title</legend>
    <div>
        <label>
            <i>String that gets translated</i>
        </label>
        <textarea>
            <i>Another string</i>
        </textarea>
    </div>
</fieldset>

Then I use preg_replace_callback to get the string between <i> tags and I replace it with a translated string, like below:

$translation = preg_replace_callback("/\<i\>(.+?)\<\/i\>/", 'translator', $html);

function translator($matches) {
    return __t($matches[1]);
}

However, when I output the html - echo $translation; - I get the following:

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>

This issue has been puzzling my head all day and I can't figure out a way to sort it out. How can I output the html and the translated string in the right order? Do I have to use DOMDocument::loadHTML, and if so how?

7
  • no issue with your code: 3v4l.org/4PhnA did you tried to echo __t($matches[1]); Commented May 26, 2016 at 0:23
  • @Akam I can't echo the __t($matches[1]) alone. They have to be echoed with the rest of the html. Why is this happening though? I think it's because __t() function echoes the string and not returning it. How can I prevent this? I can't edit the __t() function though. Commented May 26, 2016 at 0:32
  • @Akam check the sample code with the t() function echoing and not returning the string: 3v4l.org/HoprL Commented May 26, 2016 at 0:34
  • If your __t function not returning then its the problem.. Commented May 26, 2016 at 0:40
  • You could use the ob_XXX functions to capture the output buffer into a string. Commented May 26, 2016 at 0:46

1 Answer 1

2

Use the output buffering functions.

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();
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.