I have a chatlog file that looks like this (name represents screenames and text is their chat string)
name: some text
name2: more text
name: text
name3: text
I want to color all names up to the :
red.
For example: <font color=red>myname:</fontcolor> hello
How would I do this?
I'm not sure why, but this code colors everything after the colon
echo preg_replace('/(.*?):/', "<font color=#F00>$1</font>:", $output);
A correct answer to this question has been provided previously:
Look at the second answer:
PHP: insert text up to delimiter
In addition, your implementation is wrong, look at the regular expression it should start with ^ :
echo preg_replace('/(.*?):/', "<font color=#F00>$1</font>:", $output);
Should be:
echo preg_replace('/^(.*?):/', "<font color=#F00>$1</font>:", $output);
try:
echo preg_replace('/^(.*?):(.*?)$/s', "<font color=#F00>\\1</font>:\\2", $output);
EDIT: This should work (tried it):
trim(preg_replace("/(?:\n)(.*?):(.*?)/s", "<font color=#F00>\\1</font>:\\2", "\n".$str))
Final try, maybe try to explode it instead:
<?php
$content = 'name: some text
name2: more text
name: text
name3: text';
$tmp = explode("\n", $content);
for($i = 0; $i < count($tmp); $i ++) {
$tmp[$i] = '<span style="color:#F00">'.str_replace(':', '</span>:', $tmp[$i], 1);
}
echo implode("\n", $tmp);
?>
This does assume that whatever is before the colon, it won't have another colon.
My bad, I misunderstood str_replace()'s last parameter. Try this:
<?php
$tmp = explode("\n", $content);
for($i = 0; $i < count($tmp); $i ++) {
$tmp2 = explode(':', $tmp[$i]);
$tmp2[0] = '<span style="color:#F00">'.$tmp2[0].'</span>';
$tmp[$i] = implode(':', $tmp2);
}
echo implode("\n", $tmp);
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