【问题标题】:How to count each characters inside the Parenthesis如何计算括号内的每个字符
【发布时间】:2017-12-14 20:40:41
【问题描述】:

计算字符串示例中每个框中的每个字符

   $str = 'man[big man]boy[big]guy[badforreal] and others';

预期结果:

你有 6 个字符代表(人)

(男孩)你有 3 个字符

你有 10 个字符给(男)

我真的可以用 PHP 实现吗?

【问题讨论】:

  • 必须用PHP解决吗?
  • 你试过写代码吗?
  • @Basillicum 是的,如果我理解你的话,谢谢
  • 添加您尝试过的代码以及错误的详细信息。

标签: php string count output character


【解决方案1】:

扩展preg_match_all解决方案:

$str = 'man[big man]boy[big]guy[badforreal] and others';
preg_match_all('/([^\s\[\]]+)\[([^\[\]]+)\]/', $str, $matches);

if (isset($matches[1])) {
    foreach ($matches[1] as $k => $m) {
        printf("%s characters for (%s)\n", strlen(str_replace(" ", "", $matches[2][$k])), $m);
    }
}

输出:

6 characters for (man)
3 characters for (boy)
10 characters for (guy)

【讨论】:

    【解决方案2】:

    你可以试试这个

    $array = explode("]", $str);
    foreach ($array as $string){
        if( strpos($string, '[') !== false ){
            $strLabel = strstr($string, '[', true);
            $newStr .= "you have " . strlen(str_replace(["["," "], "", strstr($string, '['))) ." characters for (" . $strLabel .")<br/>";
        }
    }
    echo $newStr;
    

    预期输出

    you have 6 characters for (man)
    you have 3 characters for (boy)
    you have 10 characters for (guy)
    

    【讨论】:

      猜你喜欢
      • 2021-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-08
      • 1970-01-01
      • 2022-01-15
      相关资源
      最近更新 更多