how to remove last char from string

前端 未结 9 1121
天涯浪人
天涯浪人 2021-01-19 09:09

It might be a simple task. But I am new to PHP.

I am creating a string of values getting from database for a specific purpose.

How to remove last char from s

相关标签:
9条回答
  • 2021-01-19 09:41

    If the implode method isn't appropriate, then after your foreach loop, you can try one of these functions:

    http://www.php.net/manual/en/function.rtrim.php

    $str = rtrim($str,'#');
    

    http://php.net/manual/en/function.substr.php

    $str = substr($str,-2);
    

    If you have a 2D array, you could still use the implode func like this:

    $a = array();
    foreach( $foo as $bar )
      foreach( $bar as $part )
        $a[] = $part;
    $str = implode('##',$a);
    
    0 讨论(0)
  • 2021-01-19 09:45

    You can use Implode() for making such string instead of making it manually

    implode("##",$dataarray);
    

    BTW for removing last char you can do like below:

    substr($str,0,(strlen($str)-2));
    
    0 讨论(0)
  • 2021-01-19 09:51

    You could use PHP's function implode

    $str = implode("##", $dataarray);

    0 讨论(0)
  • 2021-01-19 09:57

    There's a few ways to go about it but:

    $str = rtrim($str, "#");
    
    0 讨论(0)
  • 2021-01-19 09:57

    http://php.net/manual/en/function.substr-replace.php

    $newstr = substr_replace($longstr ,"",-2);
    

    This will create $newstr by taking $longstr and removing the last tow characters.

    0 讨论(0)
  • 2021-01-19 09:57

    Maybe

    $str='';
    $first = true;
    foreach($dataarray as $value) {
         if(!$first) {
              $str .= "##";
         }
         else {
              $first = false;
         }
         $str .= $value;
     }
    
    0 讨论(0)
提交回复
热议问题