开发者

How can I count white spaces using substr_count() in PHP

how can I count the numb开发者_JAVA技巧er of white spaces in a file using PHP?

I have tried the substr function but it isn't working.


One way could be to remove all other characters and count what's left. You could do this with something like the following:

$count_var = preg_replace('[^\s]', '', $string);
$count = strlen($count_var);


Replace any non-whitespace with nothing, count the result:

echo strlen(preg_replace('/\S/', '', $text));

This works for any whitespace, including tabs the like.
substr_count should work fine though for regular spaces:

echo substr_count($text, ' ');


int substr_count ( string $haystack , string $needle [, int $offset = 0 [, int $length ]] ) http://br3.php.net/manual/en/function.substr-count.php

<?php
$text = 'This is a test';

echo substr_count($text, ' '); // 3
?>


use:

$test = "sadlk asd sad sda";
$whitespaces = substr_count($test," ");

substr_count()

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜