March 10, 2015

How to extract word from a string in PHP


If you wanted to extract a particular word or a string. You 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. 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.

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

} ?>


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.

<?php
$text = 'Hello World, How Are You?';
$position = strpos($text, 'World');
$word = extractWord($text, $position);
?>

This is simple example and its save your time.

Integrating Google reCAPTCHA v3 in HTML Form with PHP

  What is Google reCAPTCHA v3? Google reCAPTCHA is a free service that helps protect websites from spam and abuse. reCAPTCHA v3 is the lates...