2011-09-04 104 views
0

我有一堆看起来像这样的聊天记录:PHP:插入文字多达分隔符

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; 
+1

顺便说一下,标记已弃用! :)使用 ...另外,请记住,必须始终引用属性!像。 – Qualcuno

+0

@Qualcuno我不知道:P 要快得多 – dukevin

+0

写得更快,你的意思是?那么,我们在2011年,这不是标准。你绝对应该避免它。 – Qualcuno

回答

1

看起来不错,虽然你可以保存临时变量:

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

这可能更快,也可能不会,你必须测试:

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

hm我得到'致命错误:只有变量可以通过引用传递' – dukevin

+0

@kevin my bad。我最后一个参数犯了一个错误。 str_replace的问题在于,你不能将它约束为只做一个替换,所以这会导致在对话中使用的':'的其他出现。我用str_substr()更新了str_replace(这是一个选项),但由于这将是2个函数调用,我怀疑这可能不如爆炸效率高。 – gview

+0

我改变了程序的流程,而不是$ line逐行阅读,整个文件被读取和替换。这些解决方案仅取代第一条线,但对原始问题非常有用。 +1 – dukevin

0

也尝试这样的正则表达式:

$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); 
+0

问题是,我不知道每个人的名字是什么。他们的名字不是“name”或“name1” – dukevin

+0

然后试试这个而不是$ complete = preg_replace('/^(.*?):/',“ $ 1:”,$ line) ;由于某种原因, – steve

+0

,这颜色结束。 name: text dukevin

1

发表gview答案是简单的它但是,只是作为参考,您可以使用正则表达式来查找名称标记,并使用preg_replace()将其替换为新的html代码,如下所示:

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