user12195678
user12195678

Reputation: 3

How to count all the words with special characters

I have a question about a String i want to count all the characters in the string. Like if i have a string

"Hello world & good morning. The date is 18.05.2016"

Upvotes: 0

Views: 510

Answers (4)

Andreas
Andreas

Reputation: 23958

You can count the spaces with substr_count and add one.

echo substr_count($str, " ")+1;
// 9

https://3v4l.org/oJJkt

Upvotes: 0

Cadu De Castro Alves
Cadu De Castro Alves

Reputation: 647

The 3rd parameter of str_word_count allows you to set additional characters to be counted as words:

str_word_count($document, 0, '&.0..9');

&.0..9 means it will consider &, ., and range from 0 to 9.

Upvotes: 0

Tushar
Tushar

Reputation: 568

You can try this code.

<?php
 $file = "C:\Users\singh\Desktop\Talkative Challenge\base_example.txt"; 
 $document = file_get_contents($file); 
 $return_array = preg_split("/[\s,]+/",$document);
 echo count($return_array);
 echo $document;
?>

Hopefully it will be working fine.

Upvotes: 0

Ankur Mishra
Ankur Mishra

Reputation: 1296

You can use explode() to convert string into array and then use count() function to count length of array.

echo count(explode(' ', "Hello world & good morning. The date is 18.05.2016"))

Upvotes: 1

Related Questions