dukevin
dukevin

Reputation: 23178

PHP: Replace all instances

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);

Upvotes: 11

Views: 53085

Answers (5)

GManz
GManz

Reputation: 1659

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);

Upvotes: 1

mario
mario

Reputation: 145482

Make the regex more specific:

= preg_replace('/^(\w+):/m', ...

Or if usernames can contain non-alphanum symbols:

= preg_replace('/^(\S+):/m', "<b>$1</b>:", $output);

Upvotes: 0

Mr Coder
Mr Coder

Reputation: 8186

Try this

echo preg_replace('/([a-zA-Z0-9]*):/', "<font color=#F00>$1</font>:", $output);

Upvotes: 0

Bassem
Bassem

Reputation: 3175

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);

Upvotes: 11

steve
steve

Reputation: 586

put the : inside the font tag after $1

echo preg_replace('/^(.*?):/', "<font color=#F00>$1:</font>", $output);

Upvotes: 0

Related Questions