0

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.

1
  • 1
    You can do this using explode('-', trim('-4-25-30', '-')). Commented May 15, 2016 at 10:37

5 Answers 5

2

Try this

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

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

Sign up to request clarification or add additional context in comments.

Comments

0

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 )

Comments

0

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',
)

Comments

0
<?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

Comments

0

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
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.