当前位置: 动力学知识库 > 问答 > 编程问答 >

is there on PHP a CROP functions for the words?

问题描述:

I have a phrase with 20 words.

I'd like to crop it at 10.

Is there a ready function for this on PHP?

网友答案:

You can split the phrase into an array, then rebuild the shorter phrase from the array;

$words = explode(" ", $bigphrase);
$somewords = array_slice($words, 0, 10);
$smallphrase = implode(" ", $somewords);
网友答案:
$cropped = implode(' ', array_slice(str_word_count($text, 1), 0, 10));
网友答案:
$cropped = implode(" ", array_splice(explode(" ", $input), 0, 10));
网友答案:
$exploded = explode(" ", $string);
for($i = 0; $i < 10;$i++){
    echo $exploded[$i]." ";
}
网友答案:

You could create a function that splits the string into an array then returns the string. Something like this should do it

function crop($str, $length) {
  $str = explode(" ", $str);
  return implode(" " , array_slice($str, 0, $length));
}
网友答案:

Without using arrays, you can do this (which may work faster, not tested yet).

<?php
    $myText = "Lorem ipsum dolor sit amet consectetur adipisicing elit sed do eiusmod tempor incididunt ut labore et dolore magna aliqua";

    $result = cropWords($myText, 10);
    if($result !== false) {
        echo $result;
    }

    function cropWords($text, $cropPosition) {
        $counter = 0;
        $position = 0;
        while($counter++ < $cropPosition) {
            $position += strpos(substr($text, $position), " ");
            if($position === false) {
                return false;
            } else {
                $position++;
            }
        }
        return trim(substr($text, 0, $position));
    }
?>
网友答案:

No, in PHP there is no crop function for words in a string. PHP does not even know what a word is, and you have not specified either.

I therefore assumed that the term word or word-character in a regular expression matches your needs. If that is the case, you can just match the first 10 words in a string and drop the rest:

$string = preg_replace('~^\W*(\w+(?:\W+\w+){0,9}+).*$~', '$1', $string);

This works as well with non-word characters in front or multiple ones between words.

网友答案:

No i don't think so but you could make something like this:

<?php
function strcrop($str, $words = 10)
{
    if(substr_count($str, ' ') > 10)
        return substr($str, 0, strpos($str, ' ', $words));
    return $str;
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: