0

So I want to truncate a very long text but the problem is that I don't want x number of word or characters. I want the text truncated when it reaches a special string like ###end### or something similar e.g. I want to set where exactly it ends. edit: I know how to check the existences of the string I wasn't sure how to make the truncation

r3nt3r
  • 15
  • 6

2 Answers2

2

Maybe something like:

$pos = strpos($mystring, "###end###");
$finalText = substr ( $mystring , 0 , $pos );
Lucho
  • 1,024
  • 1
  • 15
  • 24
0

This can be done with a single call. My answer assumes that the targeted substring will exist in the string.

Code: (Demo)

$string='Here is a sample string.###end### I do not want to see any of this';
echo strstr($string,'###end###',true);  // 3rd parameter 'true' will extract everything before

Output:

Here is a sample string.

If you are uncertain if the substring will exist (and if it doesn't, you want the fullstring) this is a reliable method:

Code: (Demo)

$string='Here is a sample string.###end### I do not want to see any of this';
echo explode('###end###',$string,2)[0];  // 3rd parameter 2 will limit the number of elements produced to two

Output:

Here is a sample string.
mickmackusa
  • 43,625
  • 12
  • 83
  • 136