Jump to content

Replacing Characters


Overbleed

Recommended Posts

Hey guys, I have a quick question.

 

Im going to be making a script that will output the name of a news article along with the poster's name beside it.

 

There is only a certain amount of space where that stuff can go so I want to know how I can make it so that say after 20 characters, it ends and puts "..." beside it.

 

Is this possible with php? How would I do it?

Link to comment
Share on other sites

Yes that is the correct route WPD but you have to consider cutting a word in half, so you would want to end on a space to keep formality.

 

The following function does just that...

<?php
  function cut_str($string){
    $maxLength = 20;
    $suffix    = '...';
    $finalStr  = '';

    if(strlen($string) > $maxLength) {
      while($string{$maxLength} != ' '){
        $finalStr .= $str{$maxLength};
        $maxLength++;
      }
      return substr($string,0,$maxLength).$suffix;
    } else {
      return $string;
    }

  }

  $postTitle = 'This is my post title, just a filler really.';
  echo cut_str($postTitle);
?>

 

Tell me how it goes OverBleed :)

 

Regards, Paul.

Link to comment
Share on other sites

Or... something like this for a bit more expandability.

 

Overbleed, what this means is that you can set the maxLength for each use of this function.

 

<?php
  function cut_str($maxLength,$string){
    $suffix    = '...';
    $finalStr  = '';

    if(strlen($string) > $maxLength) {
      while($string{$maxLength} != ' '){
        $finalStr .= $str{$maxLength};
        $maxLength++;
      }
      return substr($string,0,$maxLength).$suffix;
    } else {
      return $string;
    }

  }

  $postTitle = 'This is my post title, just a filler really.';
  echo cut_str(23,$postTitle);
?>

 

Max length is now set to 23 and the result becomes => "This is my post title, just..."

 

[edit] Nice code Paul ^5!

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.