Search code examples
phpstringhighlightingdna-sequence

How to style a character in a string at specific index?


Would you please give me some guidance on how to style one character in a string at specific index? the index of this string comes from an array and in some cases the array is empty, so I only need to style the character in the string if the array is not empty

$indices = array(74, 266); 

$string  = "CAGGACACTCTTTCTAGTGTTGATTCACCTCGAAGAAGGTCTGGCCTATTAAGAGATCAAGTTCAGTTGGTAAAAAGAAGCAACTCTGCTCGTTATGAGATAGTCCCGATTCAAGATCAACTATCATTTGAGAAGGGTTTCTTTATTGTAATCCGTGCATGCCAGTTGTTGGCTCAGAAGAATGAAGGCATTGTACTGGTGGGAGTCGCTGGTCCTTCAGGGGCCGGAAAGACCATGTTTACAGAAAAGATCCTGAATGTTATGCCTAGTATTGCAATCATAAACATGGACAACTACAATGATCCCAGTCGTATCATTGATGGAAACTTCGACG";

so how do I add a surround the character at the index 74 and 266 with a span so I can give it a different style?

my data is coming from the database so I need to make it dynamic.

Thanks


Solution

  • It's fairly easy: all you need is a few substrs in a loop and to keep track of the character count.

    Here's a working code I made:

    // zero-based indices
    $indices = array(3, 10, 25);
    
    // input
    $in = 'abcDefghijKlmnopqrstuvwxyZ';
    
    $openTag = '<b>';
    $closeTag = '</b>';
    
    $out = '';
    $last = 0;
    foreach($indices as $i) {
        $fragment = substr($in, $last, $i-$last);
        $letter = substr($in, $i, 1);
        $last = $i+1;
    
        $out .= $fragment . $openTag . $letter . $closeTag;
    }
    
    $out .= substr($in, $last);
    
    // output
    echo $out;
    

    For this example, $out is abc<b>D</b>efghij<b>K</b>lmnopqrstuvwxy<b>Z</b>.


    For convenience, here's it also as a function:

    function highlightChars($text, $indices, $openTag, $closeTag) {
        $out = '';
        $last = 0;
        foreach($indices as $i) {
            $fragment = substr($text, $last, $i-$last);
            $letter = substr($text, $i, 1);
            $last = $i+1;
    
            $out .= $fragment . $openTag . $letter . $closeTag;
        }
    
        $out .= substr($text, $last);
    
        return $out;
    }