用PHP剪切字符串

时间:2011-04-11 12:30:39

标签: php string

我有一个字符串。有时它超过50个字符,有时更短。如果它更长,我想将其剪切为50(如果可能的话,在50个字符后最接近'。'。

我目前使用strlen进行检查,然后使用strings数组将每个字符复制到一个新字符串中,直到达到50(在for循环中)。这似乎是一种糟糕的方式,并且缓慢。我没办法做到'。'到目前为止......

  • 他们是一个更好的方法来削减字符串吗?
  • 怎样才能做'。'一部分?

4 个答案:

答案 0 :(得分:3)

尝试这样的事情:

<?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);
    }
}

答案 1 :(得分:3)

首先使用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);
      }
   }
}

答案 2 :(得分:0)

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

在PHP中,函数为here

例如。获得前5个字符

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

剩下的逻辑(到最近的'。')我留给你。

答案 3 :(得分:0)

这样的事情应该有效:

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