Skip to content

Instantly share code, notes, and snippets.

@gpetz
Last active August 29, 2015 14:05
Show Gist options
  • Save gpetz/2d47f84da1fea7bc2f88 to your computer and use it in GitHub Desktop.
Save gpetz/2d47f84da1fea7bc2f88 to your computer and use it in GitHub Desktop.
How to extract word from a string given a position in php
<?php
for ($i = 0; $i <= 30; $i++) {
$test = extractWord("durchfall fieber kinder", $i);
echo $i . ": " . $test . "\n";
}
function extractWord($text, $position) {
$words = explode(' ', $text);
$characters = -1;
foreach ($words as $word) {
$characters += strlen($word) + 1;
if ($characters >= $position) {
return $word;
}
}
return '';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment