Sub-string without counting blank spaces

后端 未结 3 2010
抹茶落季
抹茶落季 2020-12-21 23:07

I want to make a sub-string, where the $count only counts letters, not spaces. This is what I have so far:

$string =\"vikas tyagi php\";
$strin         


        
相关标签:
3条回答
  • 2020-12-21 23:42

    If I understand you correctly you can do it like so:

    <?php
        $string = "vikas tyagi";
        $lettercount = strlen(str_replace(' ', '', $string));
        echo $string . ' contains ' . $lettercount . ' letters';
    ?>
    

    Here I've used strlen() on a version of $string with spaces removed using str_replace()

    Addition

    I didn't understand the question

    Addition

    Here's my first crack at this, feel free to amend where you see fit:

    $string = "vikas tyagi";
    
    function my_substr($string, $start, $length)
    {
        $substr = substr($string, $start, $length);
        $spaces = count(explode(' ', $substr)) - 1;
        if ($spaces > 0)
        {
            return substr($string, $start, $length + $spaces);
        }
        return $substr;
    }
    
    echo my_substr($string, 0, 10);
    
    0 讨论(0)
  • 2020-12-21 23:45
    $arr = explode(" ",$str);
    $length = 10;
    for ($i = 0, $currIndex = 0, $finalstring = ""; $currIndex < $length; $i++){
        $finalstring .= " ".substr($arr[$i], 0, $length - $currIndex);
        $currIndex += strlen($arr[$i]);
    }
    

    Here is a demonstration: http://codepad.org/lv4KEsAi

    0 讨论(0)
  • 2020-12-21 23:47

    Simply count the spaces and add them to the desired length of the capture:

    function spaceless_substr($string, $start, $count) {
        return substr($string, $start, ($count+substr_count($string, ' ', $start, $count)));
    }
    
    $string ="vikas tyagi asd sd as asd";
    echo substr($string, 0, 14);
    // return: "vikas tyagi a"
    echo spaceless_substr($string, 0, 14);
    // return: "vikas tyagi asd" 
    
    0 讨论(0)
自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题