tags:

views:

102

answers:

2

I have data in a notepad file as following:

A   1-6
A   1-7
B   1-8
B   1-9
B   1-10
c   1-11
C   1-12
D   1-13
F   1-14
F   1-15
f   1-16

I want above data to be updated as below in the notepad file:

<strong>A</strong>  1-6
A   1-7
<strong>B</strong>  1-8
B   1-9
B   1-10
<strong>c</strong>  1-11
C   1-12
<strong>D</strong>  1-13
<strong>F</strong>  1-14
F   1-15
f   1-16

Which means adding a <strong> tag or any other tag with first character alphabetically. The data in file is sorted alphabetically (A to Z).

I want to achieve this in PHP using RegEx techniques, please help!

Thanks.

+3  A: 

I'd do something like :

$seen = array();
$file = array(
'A   1-6',
'A   1-7',
'B   1-8',
'B   1-9',
'B   1-10',
'c   1-11',
'C   1-12',
'D   1-13',
'F   1-14',
'F   1-15',
'f   1-16'
);
foreach($file as $line) {
    $L = strtoupper(substr($line, 0, 1));
    if (!isset($seen[$L])) {
        $line = preg_replace('!^(.)!', "<strong>$1</strong>", $line);
        $seen[$L] = 1;
    }
    echo $line,"\n";
}

Output:

<strong>A</strong>   1-6
A   1-7
<strong>B</strong>   1-8
B   1-9
B   1-10
<strong>c</strong>   1-11
C   1-12
<strong>D</strong>   1-13
<strong>F</strong>   1-14
F   1-15
f   1-16
M42
+1  A: 

You could do this with awk instead of grep at the command line:

example.file:

A   1-6
A   1-7
B   1-8
B   1-9
B   1-10
c   1-11
C   1-12
D   1-13
F   1-14
F   1-15
f   1-16

AWK (case-insensitive):

cat example.file | awk 'BEGIN {last=""} {if (tolower($1) != last) printf "<b>"$1"</b>"; else printf $1; print " "$2;last=tolower($1)}'

Output:

<b>A</b> 1-6
A 1-7
<b>B</b> 1-8
B 1-9
B 1-10
<b>c</b> 1-11
C 1-12
<b>D</b> 1-13
<b>F</b> 1-14
F 1-15
f 1-16

With a minor tweak, you could also just avoid printing the redundant first column entirely and summarize all the data beneath the first occurrence:

cat t | awk 'BEGIN {last=""} {if (tolower($1) != last) print "<b>"$1"</b>"; print $2;last=tolower($1)}'

Output:

<b>A</b>
1-6
1-7
<b>B</b>
1-8
1-9
1-10
<b>c</b>
1-11
1-12
<b>D</b>
1-13
<b>F</b>
1-14
1-15
1-16

If this is truly HTML, you should probably also add in your <BR> tags.

Jeff Standen