View Full Version : Challenge: Creating int from mixed string

10-22-2009, 04: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";
echo "false";

first to solve gets thanks! :)

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

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


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

10-22-2009, 05: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?

10-22-2009, 03: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 :)