給定一個字符串,例如: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'我怎樣才能修正這個正則表達式,以便在它們中包含帶有符號的單詞? –