108

I am looking for a way to pull the first 100 characters from a string variable to put in another variable for printing.

Is there a function that can do this easily?

For example:

$string1 = "I am looking for a way to pull the first 100 characters from a string variable to put in another variable for printing.";
$string2 = 100charfunction($string1);
print $string2

To get:

I am looking for a way to pull the first 100 characters from a string vari
markus
  • 40,136
  • 23
  • 97
  • 142
JoshFinnie
  • 4,841
  • 7
  • 28
  • 28

6 Answers6

230
$small = substr($big, 0, 100);

For String Manipulation here is a page with a lot of function that might help you in your future work.

Patrick Desjardins
  • 136,852
  • 88
  • 292
  • 341
  • 2
    there is problem on returning Arabic text, as they are words with combined letters if the second parameter(100) is not at end of Arabic words on the last while counting 100 it will return null. for that we will use(mb_substr($big,0,100) – SAR Feb 25 '17 at 06:29
39

You could use substr, I guess:

$string2 = substr($string1, 0, 100);

or mb_substr for multi-byte strings:

$string2 = mb_substr($string1, 0, 100);

You could create a function wich uses this function and appends for instance '...' to indicate that it was shortened. (I guess there's allready a hundred similar replies when this is posted...)

Stein G. Strindhaug
  • 5,077
  • 2
  • 28
  • 41
35

A late but useful answer, PHP has a function specifically for this purpose.

mb_strimwidth

$string = mb_strimwidth($string, 0, 100);
$string = mb_strimwidth($string, 0, 97, '...'); //optional characters for end
RJParikh
  • 4,096
  • 1
  • 19
  • 36
Coz
  • 1,875
  • 23
  • 21
24
$x = '1234567';

echo substr ($x, 0, 3);  // outputs 123

echo substr ($x, 1, 1);  // outputs 2

echo substr ($x, -2);    // outputs 67

echo substr ($x, 1);     // outputs 234567

echo substr ($x, -2, 1); // outputs 6
leek
  • 11,803
  • 8
  • 45
  • 61
markus
  • 40,136
  • 23
  • 97
  • 142
21

try this function

function summary($str, $limit=100, $strip = false) {
    $str = ($strip == true)?strip_tags($str):$str;
    if (strlen ($str) > $limit) {
        $str = substr ($str, 0, $limit - 3);
        return (substr ($str, 0, strrpos ($str, ' ')).'...');
    }
    return trim($str);
}
nickf
  • 537,072
  • 198
  • 649
  • 721
Kostis
  • 1,105
  • 8
  • 10
3

Without php internal functions:

function charFunction($myStr, $limit=100) {    
    $result = "";
    for ($i=0; $i<$limit; $i++) {
        $result .= $myStr[$i];
    }
    return $result;    
}

$string1 = "I am looking for a way to pull the first 100 characters from a string variable to put in another variable for printing.";

echo charFunction($string1);
joan16v
  • 5,055
  • 4
  • 49
  • 49