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 icon smile How to extract word from a string given a position in php

 

Like this post? Share it!

digg 48 How to extract word from a string given a position in php reddit 48 How to extract word from a string given a position in php stumbleupon 48 How to extract word from a string given a position in php delicious 48 How to extract word from a string given a position in php furl 48 How to extract word from a string given a position in php technorati 48 How to extract word from a string given a position in php google 48 How to extract word from a string given a position in php myspace 48 How to extract word from a string given a position in php facebook 48 How to extract word from a string given a position in php twitter 48 How to extract word from a string given a position in php
share save 171 16 How to extract word from a string given a position in php

No related posts.

About Clay

I am Clay who is the main writer for this website. I own a small web hosting company in Malaysia and i'm available to be hired as individual contractor on elance or odesk. You can find me on twitter.
This entry was posted in How-to, PHP and tagged . Bookmark the permalink.

Comments are closed.