2010-07-02 52 views
1

如何将包含单词和句子的文本从一段文本转换为带有PHP的斜体标签。提前致谢。将周围的下划线转换为标签

所以 -

This is _just_ a test string for the _purposes of this example_. 

将成为 -

This is <i>just</i> a test string for the <i>purposes of this example</i>. 

回答

1

基本上使用正则表达式。请注意,如果下划线出现在别处,这可能会产生不希望的效果,例如,在预先存在的HTML标签和URL中。如果是这样,你也必须尝试\ b。或者,使用现成的Wiki解析器,如果这就是你所需要的。

+0

感谢马里奥和蜥蜴,他们都很好,但我喜欢这个的简短。你能推荐任何学习regulr表达的好地方吗? – usertest 2010-07-02 16:31:18

+0

@ user201140:我最喜欢的资源是http://www.regular-expressions.info/javascriptexample.html;它具有Perl和PHP regex meta thingys的广泛概述,并且通常比PHP手册或Perl手册页更容易理解。这通常是谷歌首次在该领域进行任务。无论如何,尝试正则表达式测试工具。还有更多,甚至桌面正则表达式构建器/测试器。 – mario 2010-07-02 16:56:43

2
$content = "This is _just_ a test string for the _purposes of this example_."; 

preg_match_all("|_(.*)_|U",$content,$rows); 

foreach($rows[0] as $key=>$row) { 
    $content = str_replace($row, "<i>".$rows[1][$key]."</i>", $content); 
} 
echo $content; 

这是只是测试字符串为目的这个例子的。