如何在不切割单词PHP的情况下将字符串分成两部分?

时间:2021-07-14 03:14:38

I have this code that cuts the string $txt0 in two parts when lenght is greater than 64 characters. The problem is that sometimes cuts a word giving me a result like:

我有这个代码,当lenght大于64个字符时,将字符串$ txt0分成两部分。问题是,有时会切换一个单词给我一个结果,如:

$txt0 = "This house is ... and really pretty"


----result----

This house is...and rel

ly pretty


$array_posiciones = array (-250, -200, -150, -100, -50);
 $posicion_lineas = 0;
if ( !empty($txt0) )
  {
      if ( strlen($txt0) > 64 ) 
      {
          $lines = str_split($txt0, 40);
          $listing_title->annotateImage($draw, 0, $array_posiciones[$posicion_lineas], 0, $lines[0]."-");
          $posicion_lineas++;
          $listing_title->annotateImage($draw, 0, $array_posiciones[$posicion_lineas], 0, $lines[1]);
          $posicion_lineas++;
      } else {
          $listing_title->annotateImage($draw, 0, $array_posiciones[$posicion_lineas], 0, $txt0);
          $posicion_lineas++;
      }
  }

I am trying to draw two clean lines on a image using imagick but for the moment I can avoid to cut a word when I separated lines. Thank you and sry for my poor english. I hope you can understand the question.

我试图用imagick在图像上绘制两条干净的线条,但是当我分开线条时,我可以避免剪切一个字。谢谢你,我的英语很差。我希望你能理解这个问题。

1 个解决方案

#1


$txt0_short0=substr($txt0,0,strrpos($txt0," ",64));
$txt0_short1=substr($txt0,strrpos($txt0," ",64));

it starts from the first position of " " after the frst 64 char and uses that as the point where to split.

它从第一个64位字符后面的第一个位置开始,并将其用作分割点。

#1


$txt0_short0=substr($txt0,0,strrpos($txt0," ",64));
$txt0_short1=substr($txt0,strrpos($txt0," ",64));

it starts from the first position of " " after the frst 64 char and uses that as the point where to split.

它从第一个64位字符后面的第一个位置开始,并将其用作分割点。