hakre
hakre

Reputation: 197777

Symfony Console Output with Escape Character

I'm generating a message with sprintf() that is then to be output with the Symfony Console Component in a colored fashion:

$mask = '<info>%s</info>';
$message = sprintf($mask, 'MyString');
$output->writeln($message);

This generally works (outputs the namespace in green). However if the string ends with a backslash, the closing info-tag is ignored:

$message = sprintf($mask, 'MyString\');
$output->writeln($message);

Output:

MyString</info>
        ^^^^^^^

Obviously the backslash seems to be a sort of escape character, but how to escape it? Or how to preserve the meaning of the closing </info> tag?

So far I tried with:

Upvotes: 5

Views: 1436

Answers (1)

Federkun
Federkun

Reputation: 36944

The < character can be escaped by a \ as you already guessed. And the trailing backslashes can be escaped from Symfony v3.0.3, v2.8.3, v2.7.10 and v2.3.38 with OutputFormatter:

use Symfony\Component\Console\Formatter\OutputFormatter;

$mask = '<info>%s</info>';
$message = sprintf($mask, OutputFormatter::escape('MyString\\'));
$output->writeln($message);

Otherwise you can use:

$mask = "\033[32m%s\033[0m";
$message = sprintf($mask, 'MyString\\');
$output->writeln($message);

Upvotes: 3

Related Questions