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>
\
as "HTML" entity, the HTML entity sequence is just output verbatim and the closing tag is gone:
My\String\
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With