Wednesday, 8 October 2014

Remove last character from string PHP

<?php

$string = "a,b,c,d,e,";


//using substr

$output_str = substr("a,b,c,d,e,", 0, -1);

echo $output_str;


//using rtrim and trim

$output_str = rtrim($string, ","); //would cut trailing commas.

echo $output_str;







 

$output_str = trim($string, ","); //would cut trailing and prefixing commas.

echo $output_str;


//using
preg_replace
$output_str = preg_replace("/\,$/","",$string);

echo $output_str;


$string = preg_replace("/,$/", "", $string);
echo $string;


 // using substr_replace function 
 $output_str = substr_replace($string ,"",-1); 
 echo $output_str."\n";
//using  mb_substr multibyte version 
$output_str = mb_substr($string, 0, -1);
 echo $output_str."\n";
?>


0 comments:

Post a Comment