给定一个字符串,例如:PHP获得字符串中的每个第一个字符的位置到一个数组
$string = " this is a string ";
什么是返回一个包含一个号码,表示其首先将每个字的CSV阵列的最佳方法字符位置是这样的:
$string = " this is a string ";
^ ^^^
2 11 16 20
理想情况下,输出将只是一个数组:
2,11,16,20
到目前为止,这里是我的,但我认为这是一个有点超过我的头给我有限的技能:
$string = " this is a string ";
$string = rtrim($string); //just trim the right sides spaces
$len = strlen($string);
$is_prev_white = true;
$result = "";
for($i = 0; $i <= $len; $i++) {
$char = substr($string,$i,1);
if(!preg_match("/\s/", $char) AND $prev_white){
$result .= $i.",";
$prev_white = false;
}else{
$prev_white = true;
}
}
echo $result;
我越来越: 2,4,11,16,20,22,24, 26
这似乎是正确的答案,但我无法让他们进入我想要的格式'2,11,16,20'。如图所示,到达csv列表的最简单方法是什么? –
@TripleC,将字符串偏移量转换为csv字符串的最简单方法是使用implode函数:var_dump(implode(“,”,$ matches [0]));'给出'string'2, 11,16,20'' – RomanPerekhrest
我还有一个问题。我的一些单词中有一些符号,例如'ca#t'我怎样才能修正这个正则表达式,以便在它们中包含带有符号的单词? –