note 93913 added to function.substr-replace
| From: | admiral at nuclearpixel dot com | Date: | Tue, 06 Oct 2009 18:54:47 +0000 |
| Subject: | note 93913 added to function.substr-replace | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-161410@lists.php.net to get a copy of this message | ||
Hey everyone, I was noticing that there are a lot of ways below that people are using to write their
own string truncation functions, 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
<?php
function admiralsTruncate($string, $length){
settype($string, 'string');
settype($length, 'integer');
for($a = 0; $a < $length AND $a < strlen($string); $a++){
$output .= $string[$a];
}
return($output);
}
$my_string = 'cfcd208495d565ef66e7dff9f98764da';
echo admiralsTruncate($my_string, 6); // outputs: cfcd20
echo '<br>';
echo admiralsTruncate($my_string, 9); // outputs: cfcd20849
?>
----
Server IP: 208.69.120.35
Probable Submitter: 166.70.205.28
----
Manual Page -- http://www.php.net/manual/en/function.substr-replace.php
Edit -- https://master.php.net/note/edit/93913
Del: integrated -- https://master.php.net/note/delete/93913/integrated
Del: useless -- https://master.php.net/note/delete/93913/useless
Del: bad code -- https://master.php.net/note/delete/93913/bad+code
Del: spam -- https://master.php.net/note/delete/93913/spam
Del: non-english -- https://master.php.net/note/delete/93913/non-english
Del: in docs -- https://master.php.net/note/delete/93913/in+docs
Del: other reasons-- https://master.php.net/note/delete/93913
Reject -- https://master.php.net/note/reject/93913
Search -- https://master.php.net/manage/user-notes.php