从字符串示例
计算每个框中的每个字符 $str = 'man[big man]boy[big]guy[badforreal] and others';
预期结果:
你有6个字符(男)
你有3个字符(男孩)
你有10个字符(男)
我能在PHP中真正实现这一目标吗?
答案 0 :(得分:2)
扩展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)
答案 1 :(得分:0)
你可以试试这个
$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)