需要用php创建一个长字符串的字符映射

时间:2015-03-28 15:32:16

标签: php

我需要从一个很长的字符串创建一个字符映射,我需要得到每个字符及其在字符串中的位置,字符重复多次,所以需要它们出现在字符串中的每个位置。我想了很多,但没有任何想法。下面是一个示例字符串:

    "/9j/4AAQSkZJRgABAgEAYABgAAD/4Q8HRXhpZgAATU0AKgAAAAgABgEyAAIAAAAUAAAAVkdGAAMAAAABAAMAAEdJAAMAAAABADIAAJydAAEAAAAOAAAAAOocAAcAAAf0AA+fhgkddfevbbghhhghhhhgskfAAaaaAABBBBBBBBBBB===bbhjstdef"

2 个答案:

答案 0 :(得分:0)

听起来你正在寻找这样的东西:

$string = "/9j/4AAQSkZJRgABAgEAYABgAAD/4Q8HRXhpZgAATU0AKgAAAAgABgEyAAIAAAAUAAAAVkdGAAMAAAABAAMAAEdJAAMAAAABADIAAJydAAEAAAAOAAAAAOocAAcAAAf0AA+fhgkddfevbbghhhghhhhgskfAAaaaAABBBBBBBBBBB===bbhjstdef";

$positions = array();
for($i=0;$i<strlen($string);$i++) {
    $char = $string[$i];
    if(!isset($positions[$char])) {
        $positions[$char] = array();
    }

    $positions[$char][] = $i;
}

// Example output
foreach($positions as $key => $val) {
    printf("%s occurs at %s\n", $key, implode(',', $val));
}

输出:

A occurs at 5,6,14,16,19,21,24,25,38,39,43,46,47,48,49,51,56,57,59,60,61,62,64,65,66,67,72,73,75,76,77,78,80,81,83,84,88,89,91,92,93,94,96,99,100,104,105,107,108,109,110,112,113,114,115,116,120,121,123,124,125,128,129,155,156,160,161
B occurs at 15,22,52,79,95,162,163,164,165,166,167,168,169,170,171,172
D occurs at 26,97
E occurs at 18,54,85,106
0 occurs at 42,127
+ occurs at 130
/ occurs at 0,3,27
= occurs at 173,174,175
G occurs at 71
H occurs at 31
I occurs at 58,98
J occurs at 11,87,101
K occurs at 44
M occurs at 74,82,90
O occurs at 111,117
Q occurs at 7,29
R occurs at 12,32
S occurs at 8
T occurs at 40
U occurs at 41,63
V occurs at 68
X occurs at 33
Y occurs at 20
Z occurs at 10,36
a occurs at 157,158,159
b occurs at 140,141,176,177
c occurs at 119,122
d occurs at 70,86,103,135,136,182
e occurs at 138,183
f occurs at 126,131,137,154,184
g occurs at 13,17,23,37,45,50,53,133,142,146,151
h occurs at 34,132,143,144,145,147,148,149,150,178
j occurs at 2,179
k occurs at 9,69,134,153
o occurs at 118
p occurs at 35
s occurs at 152,180
t occurs at 181
v occurs at 139
y occurs at 55,102
4 occurs at 4,28
8 occurs at 30
9 occurs at 1

答案 1 :(得分:0)

$veryLongString = "/9j/4AAQSkZJRgABAgEAYABgAAD/4Q8HRXhpZgAATU0AKgAAAAgABgEyAAIAAAAUAAAAVkdGAAMAAAABAAMAAEdJAAMAAAABADIAAJydAAEAAAAOAAAAAOocAAcAAAf0AA+fhgkddfevbbghhhghhhhgskfAAaaaAABBBBBBBBBBB===bbhjstdef";
$positions = str_split($veryLongString);
$frequencies = array_count_values($positions);

foreach($frequencies as $character => $frequency) {
    echo sprintf(
        '%s appears %d time%s', 
        $character, 
        $frequency, 
        (($frequency != 1) ? 's' : '')
    );
    $characterPositions = array_keys(
        array_filter(
            $positions, 
            function($value) use($character) { 
                return $value === $character;
            }
        )
    );
    echo sprintf(
        ' at position%s %s', 
        (($frequency != 1) ? 's' : ''), 
        implode(',', $characterPositions)
    ), PHP_EOL;
}

Demo