Thursday, 1 September 2016

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

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

<?php

$text = 'This is a test';
 echo substr_count($text, ' '); // 3
//
$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, ' ');

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


?>

0 comments:

Post a Comment