doubingling4706 2015-11-11 19:12
浏览 29

取随机字符串,使其成为以最接近的单词结尾的155个字符

I am building a system to create dynamic descriptions for meta tags. It takes the post on the page and feeds it into a function which stripes out everything unnecessary and then takes the strlen see that its to large and creates a list of words. Now, I need to remove the right amount of words to bring the string down to 155 characters or 152 and I will add an ellipsis.

Example String (None of this is actual code its meant for sudo code)

$string = "Hello lovely Solia Avatar Community, I have a little problem and I need your help. I used to have Paint Tool SAI but my laptop ate a lot of my files, one of them being SAI. Now I am trying to get it back but I lost the website I got it from. I keep finding a website to buy it from for about $70.";

echo strlen($string); = 296

if(strlen($string) > 155) {
    // Get word amount
    $words = preg_split('/\s+/', ltrim($string), 155 + 1);
}

Now, I have the words in an array and I need to take that array and bring it down to a total strlen of 155 and stop at the nearest word and not break it awkwardly. Maybe I am going about trying to solve this problem incorrectly and I need to be using a different set of functions.

  • 写回答

1条回答 默认 最新

  • douji6940 2015-11-12 05:45
    关注

    The basic idea is to find the position of the first <kbd>space</kbd> after the first 155 characters. This can be done with strpos($string, ' ', 155). Then use substr($string, 0, $endat155) to retrieve the portion of the string from the beginning to that position.

    $endat155 = strpos($string, ' ', 155);
    $firstWords = substr($string, 0, $endat155);
    echo $firstWords;
    
    评论

报告相同问题?

悬赏问题

  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统