sameer manek
sameer manek

Reputation: 763

PHP separating numbers from string into an array

I am trying to separate numbers from a string like this: -4-25-30 with php

I have tried following things:

$fltr = array();
for($i=0;$i<count($q);$i++) {
    $odr = $q[$i]['odr'];
    $fltr = preg_match_all('/([a-z0-9_#-]{4,})/i', $odr, $matches);
}

this one gives an output: 1

and the explode function:

$fltr = array();        
for($i=0;$i<count($q);$i++){
    $odr = $q[$i]['odr'];
    $fltr = explode($odr, '-');
}

note: $odr contains the string.

this one gives an O/P: "-"

I want to fetch all the numbers from the string.

Upvotes: 0

Views: 83

Answers (5)

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

To achieve the needed result with preg_match_all function you may go via following approach:

$odr = "-4-25-30";
preg_match_all('/[0-9]+?\b/', $odr, $matches);

print_r($matches[0]);

The output:

Array
(
    [0] => 4
    [1] => 25
    [2] => 30
)

Upvotes: 0

sjsam
sjsam

Reputation: 21955

<?php
$odr="-4-25-30";
$str_array=explode("-",trim($odr,"-"));
foreach  ($str_array as $value){
printf("%d\n",$value);
}
?>

should get what you're looking for

Upvotes: 0

Richard
Richard

Reputation: 1055

I've tried to combine all the examples from above with some fixes

<?php
$q = array(array('odr' => '-4-25-30'),);

$fltr = array();
for ($i = 0; $i < count($q); $i++)
{
    $odr = $q[$i]['odr'];
    $fltr = preg_match_all('/(\d+)/i', $odr, $matches); // find 1 or more digits together
}

echo "attempt 1: \n";
echo "count: ";
var_export($fltr); // count of items
echo "\nmatches: ";
var_export($matches[0]); // array contains twice the same
echo "\n";

$fltr = array();
for ($i = 0; $i < count($q); $i++)
{
    $odr = $q[$i]['odr'];
    $trim = trim($odr, '-'); // 2nd param is character to be trimed

    $fltr = explode('-', $trim); // 1st param is separator
}

echo "attempt 2, explode: ";
var_export($fltr);
echo "\n";

Output:

attempt 1:
count: 3
matches: array (
  0 => '4',
  1 => '25',
  2 => '30',
)
attempt 2: array (
  0 => '4',
  1 => '25',
  2 => '30',
)

Upvotes: 0

Murad Hasan
Murad Hasan

Reputation: 9583

As i comment, if you want to separate all the number from the string then you need to use explode function of PHP. also you need to use trim for remove the extra - from the string.

$arr = explode('-', trim('-4-25-30', '-'));
print_r($arr); //Array ( [0] => 4 [1] => 25 [2] => 30 )

Also you can do this way,

$arr = array_filter(explode('-', '-4-25-30'));
print_r($arr); //Array ( [0] => 4 [1] => 25 [2] => 30 )

Upvotes: 0

Marc Anton Dahmen
Marc Anton Dahmen

Reputation: 1091

Try this

$fltr = explode('-', trim($odr, '-'));

I think you mixed up the delimiter with the actual string when using explode().

Upvotes: 2

Related Questions