2011-03-25 221 views

回答

2

您可以使用正則表達式:

^(\S*)\s 

其中非空白字符的第一空白之前匹配。然後你可以找到非空白字符的長度,它將成爲第一個空格的索引。

if(preg_match('/^(\S*)\s/',$input,$m)) { 
    echo "Position of first white-space is ",strlen($m[1]); 
} else { 
    echo "Now whitespace in $input"; 
} 
+0

+1 - 或者長度'/^\ S * \ S /'-1。 – Tomalak 2011-03-25 14:03:43

1

codaddict的解決方案工作得很好。我只想指出,如果您設置了PREG_OFFSET_CAPTURE標誌,則preg_match()preg_match_all()函數可以在$matches陣列中提供偏移量信息。通過這種方式,可以簡化正則表達式來只是/\s/和避免調用strlen()像這樣:

if (preg_match('/\s/', $input, $m, PREG_OFFSET_CAPTURE)) { 
    echo "Position of first white-space is ", $m[0][1]; 
} else { 
    echo "No whitespace in $input"; 
}