Michael Clarke
Michael Clarke

Reputation: 169

PHP foreach loop

I'm trying to write a script but keep getting stuck.

I have a variable $message. I want to parse it. So that everything contained between * and * could be a different color. For example:

This is message * 1

Wouldn't be effected. But

This is a *message* see how it works *again here*.

Would have message and again here in a different color.

Upvotes: 0

Views: 101

Answers (5)

Suresh
Suresh

Reputation: 131

$message = 'This is a *message* see how it works *again here*.';
$colorMessage =  preg_replace('/\*([^\*]+|[\w]+)\*/', "<span class='color2'>$0</span>", $message);

Upvotes: 0

Matt S
Matt S

Reputation: 15374

$output = preg_replace('/\*([^*]+)\*/', '<em>$1</em>', $message);

or

$output = preg_replace('/\*(.+?)\*/', '<em>$1</em>', $message);

Upvotes: 0

complex857
complex857

Reputation: 20753

With regexpes:

$in = 'This is a *message* see how it works *again here*.';
$out = preg_replace('/\*([^*]+)\*/', '<span class="color">$1</span>', $in);
print $out;

little faster than non-greedy matches.

Upvotes: 2

Mike Mackintosh
Mike Mackintosh

Reputation: 14235

I would suggest the use of preg_replace():

$message = preg_replace("#\*(.*?)\*#", "<span class=\"color-red\">\\1</span>", $message);

Upvotes: 1

GolezTrol
GolezTrol

Reputation: 116140

Use explode to split the string on the asterisks. After that, you can output each element in the array, with the right markup inbetween to change the color.

Something like this:

$parts = explode('*', $message);

$italic = false;
for ($part in $parts)
{
  if ($italic) 
    echo '<i>' . $part . '</i>';
  else 
    echo $part;

  $italic = !$italic;
}

Upvotes: 1

Related Questions