Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  • addcslashes('My\String\', '\\') - does duplicate inside and single-fy at the end:

    My\\String\</info>
    
  • &#92; as "HTML" entity, the HTML entity sequence is just output verbatim and the closing tag is gone:

    My&#92;String&#92;
    
like image 955
hakre Avatar asked Oct 19 '22 11:10

hakre


1 Answers

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);
like image 104
Federkun Avatar answered Oct 29 '22 14:10

Federkun