...

View Full Version : Challenge: Creating int from mixed string



funnymoney
10-22-2009, 03:06 AM
You might consider this task easy or hard but i don't know, it just came cross my mind.

This is the task.

1) you have a variable that is a string $string ="aB%3C%'B\^B*3%5SDb";

2) extract numbers from string called $number

3) check those numbers with this solution $solution = "335";

if this structure echoes true you have a solution



if ((int)$number == (int)$solution) {
echo "true";
}
else{
echo "false";
}


first to solve gets thanks! :)

er4o
10-22-2009, 04:17 AM
Something like this maybe:



$string = "aB%3C%'B\^B*3%5SDb";
$numbers = preg_replace("/[^0-9]/", "", $string);


or



$string = "aB%3C%'B\^B*3%5SDb";

$count = strlen($string);

for ($i = 0; $i < $count; $i++) {
if (is_numeric($string[$i])) {
$numbers .= $string[$i];
}
}

settype($numbers, "integer");

echo $numbers;

kbluhm
10-22-2009, 04:55 AM
Eh, not the first, but I have a simpler regex than was already offered, just for the heck of it:


$number = preg_replace( '/\D/', '', $string );

Very simple... homework assignment?

funnymoney
10-22-2009, 02:28 PM
Excellent! No it's not homework, just something i made up. Thought it's gonna be more complicated. I'm off thinking some tougher challanges, and will be back with questions :)



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum