Introduction to PHP -Manipulating Strings

Guest Posts Paolo Nikko Nuñal

In the last article we talked about PHP variables, in this tutorial we are going to learn how to manipulate PHP functions using the strlen() and strpos(). First things first, the strlen() function is a special string manipulation function that returns the length of a string. This is important if you are planning on getting the length of the string.

Syntax:

strlen([VARIABLE/STRING]);

<?php
   $name = "John";
   echo strlen($name);
?>


The output will be 4.

<?php

   echo strlen(Horse with no name);
?>


The output will be 18.

The strlen() function is often associated with loops and other types of functions, and is important to know when the string ends, like if you are planning on trapping a specific character.

The next function is the strpos(). This function is used in searching for a specified character or text within a string. If a match is found, it will return the index of the position of the first match. Otherwise it will return a boolean FALSE.

Syntax:

strpos([VARIABLE / STRING],[STRING TO SEARCH]);

<?php
   $txt= "The quick brown fox jumps over the lazy dog";
   echo strlen($txt,"fox");
?>


The output will be 16 since fox is located in that position. The reason of which is that the counting begins at 0 rather than 1.