如何在邮件中的“*”标签之间着色文本?
问题描述:
任何人都知道我可以做到这一点:如何在邮件中的“*”标签之间着色文本?
我想发布消息并着色“*”标签之间的所有内容。 像这样:
This [*]is[*] test [*]message[*] :)
要:
This [yellow]is[/yellow]> test [yellow]message[/yellow] :)
我wroted这样的事情,实现自己的目标:
if(preg_match_all('/\*(.*?)\*/',$message,$match)) {
$beforemessage = explode("*", $message, 2);
$message = $beforemessage[0]. " <font color='yellow'>" .$match[0][0]. "</font>";
}
Howewer它只返回:
This [yellow]is[yellow]
答
刚使用preg_replace():
$message = "This *is* test *message*";
echo preg_replace('/\*(.*?)\*/', '<font color="yellow">$1</font>', $message);
This <font color="yellow">is</font> test <font color="yellow">message</font>
preg_match_all返回匹配的数组,但你的代码永远只能替换数组中的第一场比赛。你必须遍历数组来处理其他匹配。
答
使用正则表达式时有几种方法。
一个是做匹配 - 匹配的位置和匹配长度的跟踪。然后,您可以将原始消息拆分为子字符串并将它们连接在一起。
另一种是做搜索/使用正则表达式替换。
答
试试这个,或类似的方法:
<?php
$text = "Hello hello *bold* foo foo *fat* foo boo *think* end.";
$tagOpen = false;
function replaceAsterisk($matches) {
global $tagOpen;
$repl = "";
if($tagOpen) {
$repl = "</b>";
} else {
$repl = "<b>";
}
$tagOpen = !$tagOpen;
return $repl;
}
$result = preg_replace_callback("/[*]/", "replaceAsterisk", $text);
echo $result;
''不赞成和不应该被使用。参见''并使用CSS样式和HTML类名。 –
为什么不只是[黄色] [/黄色]?不会有太大的帮助,但至少在这个例子中它是可读的。 – MightyPork
我想你应该再看看我们的代码。你会注意到你永远不会追加你的消息的其余部分。 – travis