gpt4 book ai didi

php - 从字符串中获取特定字符串?

转载 作者:搜寻专家 更新时间:2023-10-31 20:57:37 25 4
gpt4 key购买 nike

我一直在尝试从字符串中获取特定的字符串,例如从下面的这个字符串中

Scale Lengths

4 string model - E A D G
5 string model - B E A D G
6 string model - B E A D G C

B 37″

我想要这部分

4 string model - E A D G
5 string model - B E A D G
6 string model - B E A D G C

我的代码如下,我得到了正确的答案

<?php
$str = 'Scale Lengths

4 string model - E A D G
5 string model - B E A D G
6 string model - B E A D G C

B
37″';

echo getBetween($str,'Scale Lengths','37″');
function getBetween($content,$start,$end){
$r = explode($start, $content);
if (isset($r[1])){
$r = explode($end, $r[1]);
return $r[0];
}
return '';
}
?>

问题: 我的问题是我上面的代码只针对这个字符串的静态类型。例如,如果我们将 37″ 更改为 28″ 或将此数字之前的 B 更改为 C 它将开始给出错误的答案。

最佳答案

尝试像这样更改您的代码:

<?php
$str = 'Scale Lengths

4 string model - E A D G
5 string model - B E A D G
6 string model - B E A D G C

B
37″';

$get_occurence=explode(" ",$str);
$split=preg_replace('/\s+/', '', end($get_occurence));
$split=preg_replace('/^[a-zA-Z]+/', '', $split);
$getBetween=getBetween($str,'Scale Lengths',$split);
$getLength=strlen($getBetween);
$getString=substr($getBetween,0,$getLength-3);

echo $getString;
function getBetween($content,$start,$end){
$r = explode($start, $content);
if (isset($r[1])){
$r = explode($end, $r[1]);
return $r[0];
}
return '';
}


?>

我已经编辑了一些代码,所以你可以用任何你想要的动态替换 B 字符串。

<?php
$str = 'Scale Lengths

4 string model - E A D G
5 string model - B E A D G
6 string model - B E A D G C

B
37″';

$get_occurence=explode(" ",$str);
$split=preg_replace('/\s+/', '', end($get_occurence));
$split=preg_replace('/^[a-zA-Z]+/', '', $split);
$split_integer=preg_replace('/\s+/', '', end($get_occurence));
$split_integer=preg_replace('/[^a-zA-Z.]*/', '', $split_integer);
$getBetween=getBetween($str,'Scale Lengths',$split);
$getLength=strlen($getBetween);

$getString=substr($getBetween,0,$getLength-(strlen($split_integer)+1));

echo $getString;
function getBetween($content,$start,$end){
$r = explode($start, $content);
if (isset($r[1])){
$r = explode($end, $r[1]);
return $r[0];
}
return '';
}


?>

希望对你有帮助。

关于php - 从字符串中获取特定字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53809127/

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