我在数据库中有以下数据
[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/