如何使用正则表达式查找空白位置

时间:2011-03-25 13:55:40

标签: php regex

我需要找到一个字符串的第一个空格位置。

类似于:str_pos($content, ' '),但我必须使用正则表达式执行此操作,因为str_pos不会在我的内容中每次都检测到空格。

2 个答案:

答案 0 :(得分: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";
}

答案 1 :(得分:1)

codaddict的解决方案效果很好。我只是想指出,如果设置preg_match()标志,preg_match_all()$matches函数可以在PREG_OFFSET_CAPTURE数组中提供偏移量信息。这样,您可以将正则表达式简化为/\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";
}
相关问题