如何计算最后一个逗号后的字符数

How to count the number of characters after the last comma

我有一个类似于下面的字符串,想计算最后一个逗号后的字符数。

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

而且应该 return 3. 我使用了 strlen 命令,但它 returns 是整个字符串的长度。 感谢您的帮助!

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

在这种情况下,您可以使用以下代码:

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

首先将您的 String 转换为数组,然后将其反转并获得 0 索引的长度。

<?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);
?>

首先,您必须用逗号 (,) 分解字符串,然后将其存储到任何变量中。您必须传递之前用于在 END 函数中存储分解数组值的变量,因为 END 函数需要任何变量作为参数。如果您使用 END 函数并在内部执行某些操作而不是传递参数,您将收到错误消息。在你必须从 END 函数中获得 trim 值 return 以删除无用的 space 之后,然后在使用 strlen 函数获取最后一个字符串的确切计数之后。

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

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

print_r(strlen(trim(end($t))));