PDA

View Full Version : preg_match help


lavinpj1
05-11-2006, 09:32 PM
I know very little regex and this is confusing me a little...

I have a string something like...

~3,1

where I always have a ~ followed by a number between 1 and 15, followed by a , followed by another number between 1 and 15. These are all mixed into a larger string. I want to take from this the 2 numbers into 2 variables.

How would I go about doing this?

Thanks

~Phil~

GJay
05-11-2006, 09:51 PM
$pattern='#~([0-9]+),([0-9]+)#';
preg_match($pattern,$string,$matches);

$matches[1] and [2] will contain the variables.
If the string will contain more than one such arrangement, you'll need to use preg_match_all, and decide how you want the results to be put into $matches, see http://php.net/preg-match-all for the options.

lavinpj1
05-11-2006, 10:03 PM
Thanks :)

lavinpj1
05-11-2006, 10:23 PM
Actually, I seem to have confused myself again. What I want to do is have a string, e.g. "hello ~1,4hello hello ~6,2hello bye bye" and replace the ~#,# values with something of that from an array...

i.e. I have this array...


$cols = array('white',
'black',
'#000099',
'#009900',
'red',
'#663300',
'purple',
'orange',
'yellow',
'#00FF00',
'#339966',
'#00FFFF',
'#0000FF',
'#666666',
'#CCCCCC');


and I want to replace the ~x,x values with the corresponding entry from the array, e.g.

hello ~1,4hello hello ~6,2hello bye bye ~0,0

would become...

hello #000099redhello hello purple#009900hello bye bye whitewhite

Seems strange, but it has reason :P

Thanks, Phil

fci
05-12-2006, 01:22 PM
$cols = array('white', 'black', '#000099', '#009900', 'red', '#663300', 'purple', 'orange', 'yellow', '#00FF00', '#339966', '#00FFFF', '#0000FF', '#666666', '#CCCCCC');
$str = "hello ~1,4hello hello ~6,2hello bye bye ~0,0";

preg_match_all("/~(\d+),(\d+)/", $str, $matches);
$len = count($matches[0]);
for ($x=0; $x<$len; $x++)
$str = str_replace($matches[0][$x], $cols[$matches[1][$x]].$cols[$matches[2][$x]], $str);

echo $str; // hello blackredhello hello purple#000099hello bye bye whitewhite