preg_replace表示以冒号结尾的单词

时间:2012-05-10 22:38:04

标签: php

我已经尝试过查看preg_replace,除了我对正则表达式没有多少经验。

我要做的是替换以冒号结尾的文本部分,并将其加粗并在之前和之后的两个换行符之前放置一个换行符。

IE转换此文本

title1: is some text here. title2: another piece of text.

**title1:**
is some text here.

**title2:**
another piece of text

我尝试过这样的事情......

preg_replace("!\*(.*?)\*!$:","\<br \/\>\<strong\>!\*(.*?)\*!\<\/strong\>\<br \/\>",$text);

我似乎无法让它发挥作用。

有人可以帮忙吗?

由于

岸堤

3 个答案:

答案 0 :(得分:5)

preg_replace正则表达式需要分隔。所以,首先,尝试用斜杠包装你的正则表达式。其次,我不明白你的正则表达式。像/(\w+):/这样简单的东西应该有用。

preg_replace("/(\w+):/", "<br><br><b>$1</b><br>", $text);

@AndiLeeDavis编辑了处理多字标题的答案,并在开头摆脱了无关的休息:

$mtext = preg_replace("/\.?\s*([^\.]+):/", "<br><br><b>$1</b><br>", $text);
if (strcmp(substr($mtext, 0, 8), "<br><br>") == 0) $mtext = substr($mtext, 8);

答案 1 :(得分:2)

$text = 'title1: is some text here. title2: another piece of text.';

echo preg_replace('#(\w+:) (.+?\.) ?#', "<b>$1</b><br />$2<br /><br />", $text);

...给出:

<b>title1:</b><br />is some text here.<br /><br /><b>title2:</b><br />another piece of text.<br /><br />

干杯

答案 2 :(得分:0)

   $str = 'title1: is some text here. title2: another piece of text.';
   $str = preg_replace("/(\w+:)/", "\n\n**$1**\n", $str);
   echo $str;
相关问题