gpt4 book ai didi

php - preg_replace,正则表达式获取文本部分

转载 作者:可可西里 更新时间:2023-11-01 00:24:57 25 4
gpt4 key购买 nike

我有以下问题:

我有一个文本,例如以下格式:

min: 34.0 max: 79.0383 lifetime: 17% code:iweo7373333

不是固定的text Type,意思是min也可以是-7.94884444左右。我怎样才能提取零件,例如像

这样的数组
$result['min'] = 34.0;
$result['max'] = 79.0383
and so on...

我现在通过替换空格来做到这一点,然后将“min:”替换为空,“max:”、“lifetime:”……替换为“,”,然后爆炸……主要问题是有时其他变量介于最小值、最大值、...之间,因此位置不保持正确的值。

另外 - 我认为 - 这不是一个很好的编码风格或者?这可以用正则表达式或 preg_replace 实现吗?

谢谢,萨沙

最佳答案

使用 preg_replace 或正则表达式并没有什么“坏”之处。不过,解析这个未格式化的字符串当然不是理想的选择。如果您可以修改源字符串,请尝试使用 JSON 或 XML 以获得更可靠的结果。至少,即使是 url 格式也会更好(例如 min=123&max=456&limit=789)。

现在进入主要问题:

// test data
$result = array('min' => false, 'max' => false, 'lifetime' => false);

// match any occurence of min/max/lifetime followed by : followed by text (anything not a space)
if( preg_match_all('/\b(min|max|lifetime): +([^ ]+)/', $string, $matches, PREG_SET_ORDER) ) {
foreach($matches as $m) {
$result[$m[1]] = $m[2]; // put each match into $result
}
}
var_dump($result); // see what we got back

关于php - preg_replace,正则表达式获取文本部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8882660/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com