如何在php / laravel中的第二个空格后拆分字符串?

时间:2020-01-21 06:50:14

标签: php laravel

$string="112*1/25 5*112/20 456*8/20 2*569/20 156*3/40 9*789/20";

我正在尝试在第二个空格后分​​割字符串。如何实现呢?我尝试使用以下方法。

    $my_array=preg_match('/^([^ ]+ +[^ ]+) +(.*)$/', '$string', $split);

我得到的输出为1。 我想要的输出必须如下所示

    $split=array([0]=>112*1/25 5*112/20 [1]=>456*8/20 2*569/20 [2]=>156*3/40 9*789/20);

4 个答案:

答案 0 :(得分:2)

您可以尝试:

$string="112*1/25 5*112/20 456*8/20 2*569/20 156*3/40 9*789/20";

$split = array_map(
    function($value) {
        return implode(' ', $value);
    },
    array_chunk(explode(' ', $string), 2)
);

var_dump($split);

答案 1 :(得分:1)

您可以尝试

$string="112*1/25 5*112/20 456*8/20 2*569/20 156*3/40 9*789/20";
$arr = array_chunk(explode(' ',$string),2);
$res = array_map(function($v){ return implode(' ',$v);}, $arr);

工作示例:-https://3v4l.org/FLTom

答案 2 :(得分:1)

您可以使用preg_match_all

$string="112*1/25 5*112/20 456*8/20 2*569/20 156*3/40 9*789/20";

$r = preg_match_all('~[^ ]+ [^ ]+~',$string, $match);

echo '<pre>';
var_dump($match[0]);

输出:

array(3) {
  [0]=>
  string(17) "112*1/25 5*112/20"
  [1]=>
  string(17) "456*8/20 2*569/20"
  [2]=>
  string(17) "156*3/40 9*789/20"
}

答案 3 :(得分:1)

Public Class Form4
    Private _result As DataTable

    Private Sub Form4_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim dt As New DataTable
        dt.Columns.Add("col1")
        dt.Columns.Add("col2")
        dt.Rows.Add("val11", "val12")
        dt.Rows.Add("val21", "val22")
        ' at this point, we got our result from DB
        _result = dt

        For Each row As DataRow In dt.Rows
            ComboBox1.Items.Add(row("col1"))
        Next
    End Sub

    Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
        Dim selectedIndex = ComboBox1.SelectedIndex
        Dim selectedRow = _result(selectedIndex)
    End Sub
End Class