How to mark boldly sequentially triplicate and quadruplicate characters in a string?

8

I want to mark the triplicate and quadruplicate sequences of a string like this:

$string = "AAACDEAAAABBBUUDD";

And I would like to get the following result:

<b>AAA</b>CDE<b>AAAA</b><b>BBB</b>UUDD
    
asked by anonymous 22.05.2017 / 19:03

1 answer

13

PHP Version

   $string = 'AAACDEAAAABBBUUDD';
   $bold = preg_replace( '/(.){2,}/', '<b>$0</b>' , $string );

See working at IDEONE


JavaScript Version

var str = "AAACDEAAAABBBUUDD";
var res = str.replace( /(.){2,}/g, "<b>$&</b>");

See working at IDEONE


Understanding RegEx

  • (.) = any character (change by (\S) if you do not want spaces);

  • = the character previously mentioned by the first group (.) ;

  • {2,} two or more occurrences of the previous character. If you only want sequences of three or four characters, disregarding five or more, replace with {2,3} (original plus two equals, or original plus three equals).

That is, with each iterated character, we see if it is followed by 2 more occurrences of it, totaling the 3 or more desired.

Replacing <b>$0</b> ( $& in JS) takes the whole set found, and adds bold .

    
22.05.2017 / 19:14