Path: csiph.com!eternal-september.org!feeder.eternal-september.org!mx02.eternal-september.org!.POSTED!not-for-mail From: Matthew Carter Newsgroups: comp.lang.php Subject: Re: count chars but not using count_chars Date: Sat, 14 Nov 2015 23:08:41 -0500 Organization: Ahungry (http://ahungry.com) Lines: 51 Message-ID: <87mvufucom.fsf@ahungry.com> References: Mime-Version: 1.0 Content-Type: text/plain Injection-Info: mx02.eternal-september.org; posting-host="7c986cd4736462de309a749b207746fe"; logging-data="9327"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX19zNsnHewAt8vb+vnh8AsSR" User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/24.5 (gnu/linux) Cancel-Lock: sha1:sIzjC5zs6eY4wf017Zbworzu3eE= sha1:O8igHgRd3XBXJDh5ubfKscxkwWQ= Xref: csiph.com comp.lang.php:15902 Jerry Stuckle writes: > On 11/14/2015 5:42 AM, albert wrote: >> If have "Hello World World" >> how can count the spaces number? >> >> I founded this >> $str = "Hello World World"; >> $strArray = count_chars($str,1); >> >> >> but is necessary to create more code for to have the value >> foreach ($strArray as $key=>$value) >> {echo "The character ".chr($key)."was found $value time";} >> >> and filter the $key >> >> there isn't a directly function? >> >> > > Not for a specific character, there isn't. There are several ways of > doing it. For instance, using count_chars, you could use something like: > > $cts = count_chars($str, 0); // Return counts of all chars > $spacecnt = $cts[' ']; // Get number of spaces > > Alternatively, something like: > > $cts = 0; > for ($i = =; i < strlen($str); $i++) > if ($str[$i] == ' ') > $cts++; > > Or any number of ways. You could use a regex, as Pointed Head > indicated, but that can get pretty complex for a new programmer pretty > quickly - and really is overkill for something relatively simple. > > And BTW - don't worry about Pointed Head's complaints. He's a > well-known troll in this and several other newsgroups. If you have a somewhat recent version of PHP, this will work: $str = "Hello World World"; $spaces = count_chars($str,1)[32]; echo "You had {$spaces} spaces."; -- Matthew Carter (m@ahungry.com) http://ahungry.com