0

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.

3
  • Ok the script seems to be present on this site lol the italic text here is the text I would wnat to change colors (wrapped in *) Commented Sep 4, 2012 at 14:22
  • Yeah, and that looks a bit dodgy as you're using StackOverflow markup. Please add backticks (`) to the phrases. Commented Sep 4, 2012 at 14:23
  • 2
    I'm just wondering what this has to do with a foreach loop. Commented Sep 4, 2012 at 16:44

5 Answers 5

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

I would suggest the use of preg_replace():

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

1 Comment

Either or would work. I've always been partial to \\1. Makes it look less like a PHP variable.
0
$output = preg_replace('/\*([^*]+)\*/', '<em>$1</em>', $message);

or

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

1 Comment

I'd use ([^*]+) as the capture pattern, for clarity. The [^*] to strictly specify we're looking for anything that isn't an asterisk, and the + instead of the * to only format anything which contains text inside.
0
$message = 'This is a *message* see how it works *again here*.';
$colorMessage =  preg_replace('/\*([^\*]+|[\w]+)\*/', "<span class='color2'>$0</span>", $message);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.