Reputation: 21
Does anyone know PHP code that would strip any characters from string except number. But if there is space between numbers it would separate them.
Example input:
$input = '28 - 200 mm';
Output:
$num1 = 28;
$num2 = 200;
Thank you!
Upvotes: 0
Views: 158
Reputation: 1344
You would have a better chance using Regex with your problem.
But here is quick a solution :
$string = "28 - 100 mm";
$arr = explode(" ",$string);
$numbers = array();
foreach($arr as $value)
{
if(intval($value))
$numbers[] = intval($value);
}
Which results in array(2) { [0]=> int(28) [1]=> int(100) }
Upvotes: 0
Reputation: 711
<?php
$str = '28 - 200 mm';
$pattern = '#(?P<numbers>\d+)#';
if(preg_match_all($pattern, $str, $matches)){
foreach ($matches['numbers'] as $number) {
echo $number;
}
}
Upvotes: 2
Reputation: 91742
Your basic regex would look like:
#\b(\d+)\b#
^^ word boundary
^^^ one or more digits
So something like:
preg_match_all('#\b(\d+)\b#', $your_string, $results);
And the results would be stored in the $results
array, see the manual on preg_match_all
.
Upvotes: 0