php - How to style a character in a string at specific index? -
would please give me guidance on how style 1 character in string @ specific index? index of string comes array , in cases array empty, need style character in string if array not empty
$indices = array(74, 266); $string = "caggacactctttctagtgttgattcacctcgaagaaggtctggcctattaagagatcaagttcagttggtaaaaagaagcaactctgctcgttatgagatagtcccgattcaagatcaactatcatttgagaagggtttctttattgtaatccgtgcatgccagttgttggctcagaagaatgaaggcattgtactggtgggagtcgctggtccttcaggggccggaaagaccatgtttacagaaaagatcctgaatgttatgcctagtattgcaatcataaacatggacaactacaatgatcccagtcgtatcattgatggaaacttcgacg";
so how add surround character @ index 74 , 266 span can give different style?
my data coming database need make dynamic.
thanks
it's easy: need few substr
s in loop , keep track of character count.
here's working code made:
// zero-based indices $indices = array(3, 10, 25); // input $in = 'abcdefghijklmnopqrstuvwxyz'; $opentag = '<b>'; $closetag = '</b>'; $out = ''; $last = 0; foreach($indices $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 example, $out
abc<b>d</b>efghij<b>k</b>lmnopqrstuvwxy<b>z</b>
.
for convenience, here's as function:
function highlightchars($text, $indices, $opentag, $closetag) { $out = ''; $last = 0; foreach($indices $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; }
Comments
Post a Comment