如果我有一堆字符串,例如 XXX-WYC-5b ,其中XXX是1到999之间的任何值,我如何确定XXX的长度?
所以我可能有:
1:6-WYC-5b
2:32-WYC-5b
3:932-W-5b
4:22-XYQ-5b
5:914-WYC-5b
我希望它告诉我XXX的长度,所以:
1:1字符
2:2个字符
3:3个字符
4:2个字符
5:3个字符
我也想知道价值本身,所以:
1:6
2:32
3:932
4:22
5:914
我一直在想有一种方法可以使用substr_count()和explode(),但我似乎无法弄明白。非常感谢你的帮助。
答案 0 :(得分:3)
使用PHP的内置字符串位置功能。因为它从0开始计数,所以你甚至不必调整输出:
$pos = strpos($string, "-");
对于第二部分,使用PHP的子字符串函数:
return substr($string, 0, $pos);
答案 1 :(得分:0)
您可能想尝试的另一种方法:
<?php
$str[] = '6-WYC-5b';
$str[] = '32-WYC-5b';
$str[] = '932-W-5b';
$str[] = '22-XYQ-5b';
$str[] = '914-WYC-5b';
foreach($str as $v){
$result[] = getval($v);
}
function getval($value){
$seg = explode('-',$value);
return array('int'=>$seg[0],'intlen'=>strlen($seg[0]),'char'=>$seg[1],'charlen'=>strlen($seg[1]),'last'=>$seg[2],'lastlen'=>strlen($seg[2]));
}
print_r($result);
?>
outputs:
Array
(
[0] => Array
(
[int] => 6
[intlen] => 1
[char] => WYC
[charlen] => 3
[last] => 5b
[lastlen] => 2
)
[1] => Array
(
[int] => 32
[intlen] => 2
[char] => WYC
[charlen] => 3
[last] => 5b
[lastlen] => 2
)
[2] => Array
(
[int] => 932
[intlen] => 3
[char] => W
[charlen] => 1
[last] => 5b
[lastlen] => 2
)
[3] => Array
(
[int] => 22
[intlen] => 2
[char] => XYQ
[charlen] => 3
[last] => 5b
[lastlen] => 2
)
[4] => Array
(
[int] => 914
[intlen] => 3
[char] => WYC
[charlen] => 3
[last] => 5b
[lastlen] => 2
)
)