Jump to content

[SOLVED] Convert to Italics


raku

Recommended Posts

Hi,

 

I'm using the pattern '/_(.+)_/Ui' to match words/phrases surrounded with underscores and convert them to html italics. But, I would like to avoid links that may have double underscores in them. Is there a way to make the pattern only match if there is whitespace or nothing on either side of the underscores?

 

Thanks.

 

Link to comment
Share on other sites

Thanks. The only problem there is that it doesn't match near the end of sentences. For example:

 

"This is _cool_." won't italicize "cool"

 

So essentially, I would also like it to match if there is nothing on the right of the word/phrase or if there is punctuation.

Link to comment
Share on other sites

Sure.

 

<?php
$subs = array(
  '/\b_(.+)_\b/iU' => ' <em>$1</em> '
);

$text = "http://www.google.com/_testing/blah_.html";

$formatted_text = preg_replace(array_keys($subs), array_values($subs), $text);
?>

 

Thanks.

Link to comment
Share on other sites

You'll need something similar to this, which was used to ignore HTML:

 

<pre>
<?php

$data = <<<DATA
_italic_http://www.phpfreaks.com
http://www.google.com/_do_not_italicize
_abc__123_xyz
DATA;

### Isolate the URLs from the rest of the data.
$pieces = preg_split('%(http://\S+)%', $data, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);

### Analyze each piece.
foreach ($pieces as &$piece) {
	### Ignore the URLs.
	if (substr($piece, 0, 7) == 'http://') {
		continue;
	}
	$piece = preg_replace('/_([^_]+)_/', '<em>$1</em>', $piece);
}

### Reassemble.
echo $data = join('', $pieces);

?>
</pre>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.