Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 659
dukevin Avatar asked Sep 04 '11 02:09

dukevin


2 Answers

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);
like image 177
Bassem Avatar answered Nov 19 '22 05:11

Bassem


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);
like image 1
Hosh Sadiq Avatar answered Nov 19 '22 05:11

Hosh Sadiq