-3

Hi I have string variable and I need print only max 100 characters but I want dot on end. So I want print summary of string, where in the best case will be dot like 100th char,in worse case 99th car....

If the string is not a dot, I want to print it whole.

for example what I want

$longstring = "abcd. dasda. dsad.sd asd a."
$whaIWant = "abcd. dasda. dsad.sd asd a."

$longstring = "abcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdef. abcdefabcdef"
$whaIWant = "abcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdef."

How I can do it?

2 Answers2

2

You can use substr and strrpos.
Substr splits a string and strrpos finds a needle in a haystack backwards.
I use substr to pass 35 characters only to the strrpos and let it find the previous dot.
Then I use that in substr from 0 -> the dot +1 character.

$str = "string with dot. And another. Again.";
// Full string is 36 characters

$n = 35; // in your case 100
$pos = strrpos(substr($str,0,$n), ".");
If($pos === false) $pos = strlen($str);
Echo substr($str,0, $pos+1);

Edit: forgot about if no dot was found.
That makes strrpos return false. If that happens I give $pos the full length of $str.

https://3v4l.org/YS7X7

Andreas
  • 23,610
  • 6
  • 30
  • 62
-1

Use substr()

$bigString = 'this is my big string .... pretend this is a lot of chars'
$smallString = substr($bigString, 0, 100)

This will only return the first 100 characters when you use it in your template you can easily echo out the smallString and add a . at the end

Jason McFarlane
  • 2,048
  • 3
  • 18
  • 30