Ooh! Ooh! Can I play too?
function getWord($text, $pos) {
if ($pos > strlen($text)) {
return '';
}
if ($pos < 1) $pos = 1;
/* Get a copy of the string up until $pos */
$tmp = substr($text, 0, $pos);
/* Match the last word of the temporary string keeping any trailing non-word characters */
$tmp = preg_replace('/^.*?([\w\\'\-]+[^\w\\'\-]*)$/s', '\1', $tmp);
/* Append the second part of the original string back onto our temporary string */
$tmp .= substr($text, $pos);
/* Match the word at the beginning of the string and return it */
return preg_replace('/^([\w\\'\-]*).*$/s', '\1', $tmp);
}
This one counts the first character in the string as position 1. It uses regex's "word" character to find word breaks, which should vary by locale.
Edited to include apostrophes and hyphens in words. Also changed PHP tags to CODE since its nearly impossible to get backslashes right in PHP blocks. grrr