dukevin
dukevin

Reputation: 23178

PHP: insert text up to delimiter

I have a bunch of chat logs that look like this:

name: some text
name2: more text
name: text
name3: text

I want to highlight the just the names. I wrote some code that should do it, however, I was wondering if there was a much cleaner way than this:

$line= "name: text";
$newtext = explode(":", $line,1);
$newertext = "<font color=red>".$newtext[0]."</font>:";
$complete = $newertext.$newtext[1];
echo $complete;

Upvotes: 0

Views: 3422

Answers (3)

gview
gview

Reputation: 15361

Looks fine, although you can save the temp variables:

$newtext = explode(":", $line,1);
echo "<font color=red>$newtext[0]</font>:$newtext[1]";

This might be faster or might not, you'd have to test:

echo '<font color=red>' . substr_replace($line, '</font>', strpos($line, ':') , 0);

Upvotes: 1

steve
steve

Reputation: 586

also try the RegExp like this:

$line = "name: text";
$complete = preg_replace('/^(name.*?):/', "<font color=red>$1</font>:", $line);
echo $complete ;

EDIT

if their names aren't "name" or "name1", just delete the name in pattern, like this

$complete = preg_replace('/^(.*?):/', "<font color=red>$1</font>:", $line);

Upvotes: 0

Bassem
Bassem

Reputation: 3175

The answer posted by gview is the simplest it gets, however and just as a reference you can use a regular expression to find the name tag, and replace it with the new html code using preg_replace() as follows:

// Regular expression pattern 
$pattern = '/^[a-z0-9]+:?/';

// Array contaning the lines
$str = array('name: some text : Other text and stuff',
        'name2: more text : : TEsting',
        'name: text testing',
        'name3: text Lorem ipsum');

// Looping through the array
foreach($str as $line)
{
    // \\0 references the first pattern match which is "name:" 
    echo preg_replace($pattern, "<font color=red>\\0</font>:", $line);
}

Upvotes: 1

Related Questions