Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

just keep the 3 letters of a string 1

Status
Not open for further replies.

xbl12

Programmer
Dec 12, 2006
66
Hi;
if i got some strings as following

str1="asdfghjjjjjkkk";
str2="jhdkjfhaskjhfdkjsahdfhasfsdfdk.....";
str3="gf";

then i want the above just keep the first front 3 letters and then add the ".." to the end of the string

str1="asd..";
str2="jhd..";
str3="gf";

Would any one tell me how i can do that, please, Thanks
 
You can use the substr() function to cut out as many characters as you need.

Code:
$str1="asdfghjjjjjkkk";
$str2="jhdkjfhaskjhfdkjsahdfhasfsdfdk.....";
$str3="gf";


$newsub1=substr($str1,0,3) . "...";
$newsub2=substr($str2,0,3) . "...";
$newsub3=substr($str3,0,3) . "...";

You can use an If statement to check the string and see if it has less than 3 characters so you don't add the trailing "...";


----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.
 
You would run strlen() on your string to determine it's length. If the length exceeds 3 letters, you would substr($str, 0, 3) to cut off the string past the 3rd letter. Finally, you would concatenate the resulted cut string with a string of "..".

[small]Do something about world cancer today: Comprehensive cancer control information at PACT[/small]
 
Even though it's solved, I guess your using this for a loop which generates links or shortened text?

If so, what about making a function?

Code:
function genShortText($text, $len=3, $appendText="", $preText="") {
if (strlen($text)>$len) {
  $retText = $preText . substr($text, 0,$len) . $appendText;
  }
else {
  $retText = $preText . $text . $appendText;
 }
}

echo genShortText("hello there", 3, "", "...");
echo genShortText("hello there", 4, "", "...");
echo genShortText("hello there", 20,"", "...");
echo genShortText("hello there", 3, "", "");
echo genShortText("hello there", 3, "", "...");
echo genShortText("hello there", 3, '<a href="#">, "</a>");

ps. I didnt test the code, so it's to be used as psuedo.. (just wrote it in this reply)

Olav Alexander Mjelde
 
sorry, lol.. you have to add return $retText; after the else {} is closed (within the function).

Olav Alexander Mjelde
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top