PHP: insert text up to delimiter

2019-08-28 02:15发布

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;

3条回答
forever°为你锁心
2楼-- · 2019-08-28 02:32

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);
}
查看更多
我命由我不由天
3楼-- · 2019-08-28 02:43

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);
查看更多
Evening l夕情丶
4楼-- · 2019-08-28 02:46

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);
查看更多
登录 后发表回答