繁体   English   中英

在PHP中切割字符串

[英]Cutting a string in PHP

我有一个字符串。 有时长度超过50个字符,有时更短。 如果更长,我希望将其剪切到50个字符(或尽可能在50个字符后最接近的'。')。

我目前使用strlen进行检查,然后使用字符串数组将每个字符复制到新字符串中,直到达到50(在for循环中)。 这似乎是一个不好的方法,而且很慢。 我无能为力。 到目前为止

  • 他们是割断绳子的更好方法吗?
  • 一个人该怎么做。 部分?

尝试这样的事情:

<?php

//somehow your $text string is set

if(strlen($text) > 50) {

    //this finds the position of the first period after 50 characters
    $period = strpos($text, '.', 50);

    //this gets the characters 0 to the period and stores it in $teaser
    $teaser = substr($text, 0, $period);

}

感谢@Michael_Rose,让我们对其进行更新以获取更安全的代码

<?php

//somehow your $text string is set
$teaser = $text;
if(mb_strlen($text) > 50) {

    //this finds the position of the first period after 50 characters
    $period = strpos($text, '.', 50);
    //this finds the position of the first space after 50 characters
    //we can use this for a clean break if a '.' isn't found.
    $space = strpos($text, ' ', 50);

    if($period !== false) {
        //this gets the characters 0 to the period and stores it in $teaser
        $teaser = substr($text, 0, $period);
    } elseif($space !== false) {
        //this gets the characters 0 to the next space
        $teaser = substr($text, 0, $space);
    } else {
        //and if all else fails, just break it poorly
        $teaser = substr($text, 0, 50);
    }
}

首先使用strpos查找“。” 在前50个字符之后(例如@ohmusama说过),但一定要检查返回值并使用mb_strlen

$teaser = $text;
if (mb_strlen($text) > 50) {
   $period = strpos($text, '.', 50);
   if ($period !== false) {
      $teaser = substr($text, 0, $period);
   } else {
      // try finding a space...
      $space = strpos($text, ' ', 50);
      if ($space !== false) {
         $teaser = substr($text, 0, $space);
      } else {
         $teaser = substr($text, 0, 50);
      }
   }
}

您需要做的是从字符串中获取“子字符串”。

在PHP中,功能在这里

例如。 获得前5个字符

echo substr('abcdef', 0, 5); //returns "abcde"

剩下的逻辑(最接近的“。”)我留给您。

这样的事情应该起作用:

$string = substr($string, 0, 
    min(strpos($string, '.') >= 0? strpos($string, '.') : 50, 50));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM