tags:

views:

42

answers:

3

How would I convert uderscores surrounding words and sentences from a chunk of text into italic tags with PHP. Thanks in advance.

So -

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

Would become -

This is <i>just</i> a test string for the <i>purposes of this example</i>.
+2  A: 
$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;

This is just a test string for the purposes of this example.

Lizard
+1  A: 

Basically with regular expressions. Note that this might have undesired effects, if underscores appear elsewhere, e.g. in pre-existing HTML tags and URLs. If so, you'll have to experiment with \b as well.

preg_replace('/_(\w[^<>\n]+?\w)_/', '<i>$1</i>', $text);

Or, use a ready-made Wiki parser, if that's what you need.

mario
Thanks Mario and Lizard, they both work well but I like the shortness of this one. Can you recommend any good places to learn regulr expressions?
usertest
@user201140: My favourite resource is http://www.regular-expressions.info/javascriptexample.html; It has an extensive overview of Perl and PHP regex meta thingys, and it's often more understandable than the PHP manual or Perl man pages. It's often the first Google result for quests in that area. Anyway, try the regex test tool. There exist more, even Desktop regular expression builders/testers.
mario
A: 
  1. Visit http://daringfireball.net/projects/markdown/ to learn Markdown syntax.
  2. Visit http://michelf.com/projects/php-markdown/ to download and install a PHP version.
  3. Call $html = Markdown("_text_"); from your PHP.
Karmastan
Thanks I'll check it out.
usertest