Posted By

jatkins on 01/31/11


Tagged

String text word adjacent


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

virendrakryadav


Find adjacent words


 / Published in: PHP
 

Released into the public domain. Always supply $position as the index of a character within $text that is not a space.

  1. function edge_of_word($text, $position, $left = false) {
  2. $first_space = strpos($text, ' ');
  3. if(!$left&&$first_space!==false&&$position<$first_space)
  4. $position = $first_space;
  5. $last_space = strrpos($text, ' ');
  6. if($last_space!==false&&$position>$last_space)
  7. $position = $left ? $last_space : strlen($text);
  8. if(strpos($text, ' ', $position)!==false) {
  9. while($text[$position]!=' '&&((!$left&&$position<strlen($text))||($left&&$position>0))) {
  10. $position += $left ? -1 : 1;
  11. }
  12. }
  13. return $position;
  14. }
  15.  
  16. function find_adjacent_words($text, $position, $word_count, $left, $positions_only = false) {
  17. if($left===3) {
  18. $adjacent_words = array();
  19. $adjacent_words[] = find_adjacent_words($text, $position, $word_count, true, $positions_only);
  20. $adjacent_words[] = find_adjacent_words($text, $position, $word_count, false, $positions_only);
  21. return $adjacent_words;
  22. }
  23. else {
  24. $position = edge_of_word($text, $position, $left);
  25. $original_position = $position;
  26. $current_word_count = 0;
  27. while((($left&&$position>0)||(!$left&&$position<strlen($text)))&&$current_word_count<=$word_count) {
  28. if($text[$position]==' ')
  29. $current_word_count++;
  30. $position += $left ? -1 : 1;
  31. }
  32. $start_position = $left ? $position == 0 && $text[0] != ' ' ? $position : $position + 1 : $original_position;
  33. $length_of_words = $left ? $original_position - $position : $position - $original_position;
  34. return $positions_only ? array($start_position, $length_of_words) : trim(substr($text, $start_position, $length_of_words));
  35. }
  36. }

Report this snippet  

You need to login to post a comment.