Advertisement
gitlez

YA: Sampling a String at a Space WC

Apr 21st, 2012
43
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 0.98 KB | None | 0 0
  1. <?php
  2.  
  3. /*    Simple function to sample a string, at a space.  Default Length is 80   */
  4. function sample($string, $length=80){
  5.     $string = substr($string, 0, $length);
  6.     return substr($string, 0, strrpos($string, ' '));
  7. }
  8.  
  9. $block = "This is some string. I think it needs to continue for a while, but I'm not entirely sure where to cut it. So I think I will simply keep adding to it, while not counting the neccessary characters for the length. Knowing this would allow me to know when to cut the string.";
  10.  
  11.  
  12. $sample = sample($block);
  13. echo $sample . '<br>';
  14. echo 'Strlen: ' . strlen($sample) . '<br>';
  15.  
  16. /*    Ouputs:
  17. This is some string. I think it needs to continue for a while, but I'm not
  18. Strlen: 74
  19.     */
  20.  
  21. $sample2 = sample($block, 120);
  22. echo $sample2 . '<br>';
  23. echo 'Strlen: ' . strlen($sample2) . '<br>';
  24.  
  25. /*    Outputs:
  26. This is some string. I think it needs to continue for a while, but I'm not entirely sure where to cut it. So I think I
  27. Strlen: 118
  28.     */
  29.  
  30. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement