PHP - SPLessons

PHP Strings

Chapter 8

SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

PHP Strings

PHP Strings

shape Description

String is a collection of characters.In this chapter, string functions and their usage to manipulate strings is discussed.

PHP String Functions

shape Description

Some of the PHP string functions will be discussed below:

String Length

shape Description

strlen() PHP function is used to find the string length.

shape Program
Description

shape Example

<!DOCTYPE html>
<html>
	<body>
		<?php echo strlen("SP Lessons"); ?>
	</body>
</html>

Output:

Reverse the String

shape Description

strrev() PHP function is used to reverse the string.

<!DOCTYPE html>
<html>
	<body>
		<?php echo strrev("SP Lessons"); ?>
	</body>
</html>

Output:

Replace text within a string

shape Program
Description

<!DOCTYPE html>
<html>
	<body>
		<?php 
			echo str_replace("Lessons", "Programming", "SP Lessons"); 
		?>
	</body>
</html>

Output:

In the above program, Lessons is replaced with Programming in the string SP Lessons.

Text position in PHP strings

shape Description

strpos() PHP function is used to find the specific text within a string.

If the function matches then the function returns the first character position of the text in the string. If the text didn’t match then the function returns false.

<!DOCTYPE html>
<html>
	<body>
		<?php echo strpos("SP Lessons", "Lessons"); ?>
	</body>
</html>

Output:

Count the Number of words in a string

shape Description

str_word_count(); PHP function is used to count the number of words in a string.

<!DOCTYPE html>
<html>
	<body>
		<?php echo str_word_count("Welcome to the SP Lessons"); ?>
	</body>
</html>

Output:

Summary

shape Key Points

  • String is a collection of characters.
  • strrev() PHP function is used to reverse the PHP strings.
  • strpos() PHP function is used to find the specific text within a string.