PHP string functions – substr

The substr function is used to extract a portion of a string from a larger string. For example, substr can be used to extract a word from a sentence. This tutorial also shows how to combine the substr function with the strpos and strlen functions. Watch the video below and then scroll down to see the sample code.

Sample PHP code:

<?php
  $mystring = "The quick brown fox jumps over the lazy dog";
  $find = "dog";
  $start = strpos($mystring,$find);
  $stop = strlen($find);

  // will extract the word 'dog' from the string
  echo substr($mystring,$start,$stop) , "</br>";
  
  // will display each letter from the string on a new line
  $mystring_length = strlen($mystring);
  for($i=0;$i<$mystring_length;$i++){
    echo substr($mystring,$i,1),'</br>';
  }
?>