我有一堆看起来像这样的聊天记录:
name: some text
name2: more text
name: text
name3: text
我想强调的只是名字。 我写了一些代码,应该这样做,但是,我不知道是否有比这更清洁的方式:
$line= "name: text";
$newtext = explode(":", $line,1);
$newertext = "<font color=red>".$newtext[0]."</font>:";
$complete = $newertext.$newtext[1];
echo $complete;
看起来不错,但你可以保存临时变量:
$newtext = explode(":", $line,1);
echo "<font color=red>$newtext[0]</font>:$newtext[1]";
这可能会更快,也可能不会,你必须测试:
echo '<font color=red>' . substr_replace($line, '</font>', strpos($line, ':') , 0);
发表gview答案是它得到最简单的,但是,只是作为一个参考,你可以使用正则表达式查找的姓名标签,并用新的HTML代码中使用的preg_replace(替换)如下:
// 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);
}
也尝试这样的正则表达式:
$line = "name: text";
$complete = preg_replace('/^(name.*?):/', "<font color=red>$1</font>:", $line);
echo $complete ;
编辑
如果他们的名字不是“名”或“名1”,只是在图案删除名称,这样
$complete = preg_replace('/^(.*?):/', "<font color=red>$1</font>:", $line);