php - 将多个方括号值转换为数组php

标签 php regex arrays

我在数据库中有以下数据

[508] [blah-blah-blah] Random Text
[510] [hello-hello-hello] More random text
[542] [stuff-stuff-stuff] Even more text

这存在于相当多的数据库单元中。整个文本 block 都在一个单元格中,每行文本都用回车符分隔。

理想情况下,我希望将每行第一个方括号中的数字转换为数组值。我想要最终得到的数据是:

array(508,510,542)

更重要的是,我想了解如何有效地将第一个数据结构放入数组中。我觉得应该有一种简单有效的方法来使用它,但是,除了一些非常复杂的正则表达式之外,我不知道如何做到这一点:(

任何帮助都会很神奇!

最佳答案

在 PHP 中,您可以使用 lookarounds 来匹配数字。使用 preg_match_all()

获取文字括号
<?php

    $string = '[508] [blah-blah-blah] Random Text
    [510] [hello-hello-hello] More random text
    [542] [stuff-stuff-stuff] Even more text';
    preg_match_all ('!(?<=\[)([0-9]+)(?=\])!',$string,$matches);
    print_r($matches[0]);

?>

输出

Array
(
    [0] => 508
    [1] => 510
    [2] => 542
)

要处理数据库中的所有记录,您可以执行以下操作:

    $result = mysqli_query($sql);
$records = array(); 
while ($row = mysqli_fetch_array($result)){


        preg_match_all ('!(?<=\[)([0-9]+)(?=\])!',$row['my_text_field'],$matches);
        foreach($matches[0] as $value){     
        $records[]=$value;
        }

}

print_r($records);      

关于php - 将多个方括号值转换为数组php,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17098924/

相关文章:

python - 删除 numpy 数组中第一次出现的元素

c++ - 如何根据构造函数参数填充 const 成员数组?

php - 页面关闭后继续 php exec() ffmpeg

php - 在 mysqli 中带参数执行

php - 在 jQuery 中触发 Zend FlashMessenger

javascript - 过滤结果是一个对象数组,就像使用 lodash 的operator(%oil%)

php - mysql 结果返回 ?(问号)而不是 Ö 等

regex - Django 字段正则表达式验证

r - 如何用 R 在字符串中的最后一个斜杠后用 "_"替换空格

javascript - JS正则表达式替换两个字符或单词之间的句子