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
https://forums.phpfreaks.com/topic/216684-replacing-characters/
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.

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!

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.