2017-10-31 11 views
2

次のような文字列があり、最後のカンマの後にある文字の数を数えたいと思います。最後のカンマの後の文字数を数える方法

$test = "apple, orange, green, red"; 
$count = strlen($test); 
echo "$count"; 

、それは私がSTRLENコマンドを使用しているが、それは文字列全体の長さを返します。3. を返す必要があります。 ありがとうございます!

$test = "apple, orange, green, red"; 
$ex = explode(',',$test); 
$ex = array_reverse($ex); 
echo strlen(trim($ex[0])); 

最初の配列にあなたの文字列を変換して、それを逆にして0インデックスの長さを取得する:あなたがコードを次の中から使用することができます。この場合

+2

'$カウント=のstrlen関数(終了(、 ''($テストを爆発)));' – splash58

+0

OPが要求されたように、これは、4ない3を返し –

答えて

0
$splitString = explode(',', $test); 
echo strlen($splitString[count($splitString)-1]); //it will show length of characters of last part 
+0

ことを確認し@alex。 – bumperbox

+0

Naveed、それは素晴らしい作品ありがとう! – Alex

1

1
<?php 
$test = "apple, orange, green, red"; 
// Exploded string with ,(comman) and store as an array 
$explodedString = explode(",", $test); 
// with end() get last element 
$objLast = end($explodedString); 
// remove white space before and after string 
$tempStr = trim($objLast); 
//With strlen() get count of number of characters in string 
$finalStringLen = strlen($tempStr); 
print_r("Length of '".$tempStr."' is ".$finalStringLen); 
?> 
+0

これは、要求されたOPが – bumperbox

+0

@bumperboxであるため、3ではなく4を返します。トリミングするのを忘れてしまいました。 –

0

まず、文字列をカンマ(、)で爆発させてから変数に格納する必要があります。 END関数は任意の変数をパラメータとして必要とするため、END関数に展開された配列の値を格納するために以前に使用した変数を渡す必要があります。 END関数を使用して、パラメータを渡すのではなく何かを実行すると、エラーが発生します。無駄なスペースを取り除くためのEND関数からの戻り値をトリムした後、最後の文字列の正確なカウントを得るためにstrlen関数を使います。

$test = "apple, orange, green, red"; 

$t = explode(",",$test); 

print_r(strlen(trim(end($t)))); 
関連する問題