2012-05-10 98 views
3

我试着寻找到了preg_replace结尾的单词,但我有一个正则表达式没有太多的经验。的preg_replace用冒号

我试图做的是更换一个冒号结尾的文本部分,使之大胆,把一个换行符在前后2换行符。

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

我似乎无法得到它工作。

任何人都可以帮忙吗?

感谢

安迪

+0

您的所有文字是否总是像这样?即:标题:正文。标题:身体。标题:身体。 – Jake

+0

你知道问题出在替换还是模式? – Jake

+0

数据库中没有它的文本字段。我想采取任何这样的文字--->允许:该项目的林地清理目前等于等等等等。合同:与沿海Projectsblah等等等等民事合同.....和分裂文成一些更可读...... –

回答

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

谢谢你的工作。 –

+0

@Ansari我实际上学到了我所知道的关于正则表达式模式的一切。你知道我们的选择是“更好”还是仅仅是个人喜好? – Jake

+0

“以冒号结尾的文本部分”总是只有一个单词? Duh – Johanness

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 /> 

干杯

+0

好吧,我得到了最后一个错误,但这一个工作正常。感谢这么多人... preg_replace(“/(\ w +):/”,“

$ 1
”,$ row_publish_comment ['comment']); –

+0

@AndiLeeDavis我修正了RegEx,不用客气。如果有帮助,请考虑对投票答案进行投票(如果可以的话)。谢谢。 – Madbreaks

+0

感谢它的所有伟大的东西。 –

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