How to extract word from a string given a position in php

Today i wanted to extract a particular word or text (if the word doesn't make sense) given a position in a string. I tried to search this for php platform but couldn't really find an answer for it. In facts, i cannot find any through google for such functionality in php. However, i manage to find it on python. It was actually pretty simple and straight forward and i believe most of people will get it in one look. But we don't revamp the wheel so here you go.

      function extractWord($text, $position){
         $words = explode(' ', $text);
         $characters = -1; 
         foreach($words as $word){
            $characters += strlen($word);
            if($characters >= $position){
               return $word;
            }   
         }   
         return ''; 
      }   

pretty easy isn't it? The above will basically split the string into individual word and loop these words and calculate the total position. If the position of the total characters is larger or equal to the position you provide, we have reach the word that we want. Here is a little example on how to extract word from a string given a position.

$text = 'This is an example of how to extract word from a string given a position in php
$position = strpos($text, 'examp');
$word = extractWord($text, $position); // return example

It's pretty simple and straight forward but it does save some time and focus on something more important. Hope it helps 🙂

Share
Livedrive Simple, Secure Online Backup Increase sales with social commerce at BigCommerce. Learn More!