PHP - 如何找到只拉出字符串中的整数,用两个句点分隔整数?

时间:2013-01-11 01:38:21

标签: php string strip

说我有这样的字符串:

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

我如何拉出每个整数,剥离句点并将它们存储到数组中?

6 个答案:

答案 0 :(得分: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.
?>

答案 1 :(得分: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

答案 2 :(得分: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);
?>

答案 3 :(得分: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 )

答案 4 :(得分:0)

试试这个..

$string = '.30..5..12..184..6..18..201..1.';
$new_string =str_replace(".", "",  str_replace("..", ",", $string));
print_r (explode(",",$new_string));

答案 5 :(得分:0)

一线解决方案:

print_r(explode("..",substr($string,1,-1)));