Jump to content

preg_replace?


pootsey

Recommended Posts

Right guys,

 

basically what I'm trying to do is seperate a string ie

 

$string = "onetwothreefourfive"

 

and then apply two repeating html codes to each, ie one would get blue, two would get red, three would get blue, four would get red and so on.

 

Any idea how to do this?

 

thanks!

Link to comment
Share on other sites

I'm not so good at regex, but you could just use str replace

 

<?php
$string = "onetwothreefourfive";

$array = array("one","two","three","four","five");
function color($c,$txt){ return "<font color=\"".$c."\">".$txt."</font>";  }
$repl = array(color('blue','one'),color('red','two'),color('blue','three'),color('red','four'),color('blue','five'));

echo str_replace($array,$repl,$string);
?>

Link to comment
Share on other sites

ah actually, just realised something with it, the colours dont repeat, my one twothreefourfive was a bad example.

 

What I actually meant was for example the string would be a value (a username to be specific) pulled from a database which I want coloured like above.

 

So it could be any amount of characters but i still want it to be coloured like that.

 

Anyway of that happening?

Link to comment
Share on other sites

No, you could do something like this.

 

<?php
function color($c,$txt){ return "<font color=\"".$c."\">".$txt."</font>";  }

$sql = "SELECT * FROM `users` ORDER BY username ASC";
$res = mysql_query($sql) or die(mysql_error());

$x = 0;
while($row = mysql_fetch_assoc($res)){
if($x % 2){
	echo color('red',$row['username']) . " ";
}else {
	echo color('blue',$row['username']) . " ";
}

$x++;
}
?>

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.