PHP截断函数

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PHP截断函数相关的知识,希望对你有一定的参考价值。

Hey everyone, I was noticing that there are a lot of ways that people are using to write their own string truncation functions wit the use of other functions like 'substr_replace', but it kinda seemed like a lot of them went a bit too far out to make any sense to a n00b. Not that I am one anymore, but I though I'd add a note on this topic myself, in hopes that it might help others understand things a little better.

Here's a concept that some people don't know about, or remember to use often enough; You can actually pull individual characters out of a string by referencing that string as though it were an array. Example: If I have the string $s = 'cat', I can use $s[0] to actually get out only the first character of that string, 'c'. I use that same principle below, but I just use a loop to iterate through a string and add the characters to the output variable one by one until the $lenth param has been reached, or until the end of the string.

I hope this can help someone out!

-Admiral Potato
  1. <?php
  2.  
  3. function admiralsTruncate($string, $length){
  4. settype($string, 'string');
  5. settype($length, 'integer');
  6. for($a = 0; $a < $length AND $a < strlen($string); $a++){
  7. $output .= $string[$a];
  8. }
  9. return($output);
  10. }
  11.  
  12.  
  13. $my_string = 'cfcd208495d565ef66e7dff9f98764da';
  14.  
  15. echo admiralsTruncate($my_string, 6); // outputs: cfcd20
  16.  
  17. echo '<br>';
  18.  
  19. echo admiralsTruncate($my_string, 9); // outputs: cfcd20849
  20.  
  21. ?>

以上是关于PHP截断函数的主要内容,如果未能解决你的问题,请参考以下文章

php 一个自定义的try..catch包装器代码片段,用于执行模型函数,使其成为一个单行函数调用

PHP截断函数mb_substr()详细介绍

strtok函数

超级有用的9个PHP代码片段

21个常用代码片段

PHP文件包含