How to count space in a text statement in PHP
Asked Answered
B

4

14

How can we count space between text in PHP?

example: hi how are you?

spaces: 3

Is there a way to count spaces?

Language: Only PHP

Borchers answered 23/6, 2009 at 17:34 Comment(0)
K
49

Use this:

substr_count($text, ' ');
Kahler answered 23/6, 2009 at 17:37 Comment(1)
What if a string has two spaces between two words?eg "New World".Deepsix
A
2

You're looking for preg_match_all.

$numSpaces = preg_match_all('/[ ]/', $testStr, $matches);
Anatolia answered 23/6, 2009 at 17:37 Comment(0)
C
1
$arr = count_chars($str,1);
echo $arr[32];
Carding answered 23/6, 2009 at 17:37 Comment(1)
This way still works, but it's really a round-about way, since the substr_count() function exists.Caramelize
D
0
$text   = "Biography of the author of Riyād al-Sālihīn";

$spaces = substr_count($text,' ') ?: 0; // if override spaces from sentences

$data   = substr($text,0,$length + $spaces); //`enter code here
Dichromatic answered 24/9, 2022 at 11:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.