I.calculate Length of A String II - Count The Number of Words in String
I.calculate Length of A String II - Count The Number of Words in String
I.calculate Length of A String II - Count The Number of Words in String
Experiment – 5
Title: a. Write a PHP program-
i.Calculate length of a string
ii.Count the number of words in string
Without using string functions
b. Write a simple PHP program to demonstrate use of various built-
in functions.
Roll No.: 29 Name: Mehraan Khan
2. Requirements:
Personal Computer, Windows XP or above operating system, XAMPP (PHP,
APACHE, MYSQL), Microsoft Word
3. Theory:
Page 1 of 5
Page 2 of 5
Page 3 of 5
4. Program Code:
i. Write a PHP script to Calculate length of a string Without using string functions
$inpstr="abcd";
$tmp = '';
$i = 0;
while (isset($inpstr[$i])){
$tmp .= $inpstr[$i];
$i++;
}
echo $i;
ii. Write PHP script to Count the number of words in string Without using string
functions
<?php
function get_num_of_words($string) {
$string = preg_replace('/\s+/', ' ', trim($string));
$words = explode(" ", $string);
return count($words);
}
$str = " Have A Nice Day :) ";
// Function call
$len = get_num_of_words($str);
echo "The Number of words are:-",$len;
?>
Page 4 of 5
iii. Write a simple PHP script to demonstrate following built-in functions:
str_word_count( ), strlen( ), strrev( ), strops( ), str_replace( ), ucwords( ),
strcmp( ), strtoupper( ), strtolower( )
<?php
echo"Count Number of Words: ";
echo str_word_count("How are you!")."</br>";
echo "Count the Length of string: ";
echo strlen("Hello world!")."</br>";
echo "Reverse the String: ";
echo strrev("Hello world!")."</br>";
echo "Convert to Upper Case: ";
echo strtoupper("yukta!")."</br>";
echo "Convert to Lower Case: ";
echo strtolower("MY NAME IS MEHRAAN!")."</br>";
echo "Compare strings: ";
echo strcmp("Hello world!","Hello world!")."</br>";
echo "Find position of First occurence: ";
echo strpos("Hello world!", "world")."</br>";
echo "Replace string: ";
echo str_replace("world", "Dolly", "Hello world!")."</br>";
echo "Convert First Character: ";
echo ucwords("hello world")."</br>";
?>
6. Conclusion: Hence we have learned to write a simple PHP program to demonstrate use of
various built-in functions and calculate length of a string count the number of words in string.
Page 5 of 5