0

假设我有一个这样的字符串:

$string = '.30..5..12..184..6..18..201..1.'

我将如何提取每个整数,去除句点并将它们存储到数组中?

4

6 回答 6

3

你可以用这个。您将字符串按所有句点分开……但这仅在完全一样的情况下才有效;如果中间还有其他东西,例如 25.sdg.12 它就不起作用。

    <?php
    $my_array = explode("..",$string);
    $my_array[0] = trim($my_array[0]); //This removes the period in first part making '.30' into '30'
  ///XXX  $my_array[-1] = trim($my_array[-1]); XXX If your string is always the same format as that you could just use 7 instead.

我检查了 PHP 不支持负索引,但您可以计算数组列表并使用它。前任:

$my_index = count($my_array) - 1;
$my_array[$my_index] = trim($my_array[$my_index]); //That should replace '1.' with '1' no matter what format or length your string is.
?>
于 2013-01-11T01:40:54.857 回答
0

我能想到的。

<?php
$string = '.30..5..12..184..6..18..201..1.';
$r_string = str_replace("..", ",", $string);
$r_string = str_replace(".", ",", $r_string);
print_r(explode(",", $r_string));
?>

或者如果你想在一个变量中的数组

<?php
$string = '.30..5..12..184..6..18..201..1.';
$r_string = str_replace("..", ",", $string);
$r_string = str_replace(".", ",", $r_string);
$arr_ex = explode(",", $r_string);
print_r($arr_ex);
?>
于 2013-01-11T01:47:00.437 回答
0

其他人发布了这个但随后删除了他们的代码,它按预期工作:

<?php
$string = '.30..5..12..184..6..18..201..1.';

$numbers = array_filter (explode ('.', $string), 'is_numeric');

print_r ($numbers);
?>

输出:

Array (
[1] => 30
[3] => 5
[5] => 12
[7] => 184
[9] => 6
[11] => 18
[13] => 201
[15] => 1 )
于 2013-01-11T01:50:18.990 回答
0

尝试这个 ..

$string = '.30..5..12..184..6..18..201..1.';
$new_string =str_replace(".", "",  str_replace("..", ",", $string));
print_r (explode(",",$new_string));
于 2013-01-11T01:50:30.070 回答
0

一线解决方案:

print_r(explode("..",substr($string,1,-1)));
于 2013-01-11T01:51:26.213 回答
0

这会将您的字符串分解为一个数组,然后循环获取数字。

$string = '.30..5..12..184..6..18..201..1.';
$pieces = explode('.', $string);

foreach($pieces as $key=>$val) {
    if( is_numeric($val) ) {
    $numbers[] = $val;
    }
}

您的号码将在数组中$numbers

于 2013-01-11T01:43:18.900 回答