$re = '/^
([^\|]+?)(?:\|\1)*
(\|(?!\1)[^\|]+?)?(?:\|\1|\2)*
((?!\|\1|\2)\|[^\|]+?)?(?:\|\1|\2|\3)*
((?!\|\1|\2|\3)\|[^\|]+?)?(?:\|\1|\2|\3|\4)*
((?!\|\1|\2|\3|\4)\|[^\|]+?)?(?:\|\1|\2|\3|\4|\5)*
((?!\|\1|\2|\3|\4|\5)\|[^\|]+?)?(?:\|\1|\2|\3|\4|\5|\6)*
$/mx';
$str = 'TPL1
TPL1|TPL1
TPL2
TPL1|TPL2
TPL2|TPL2|TPL1
TPL1|TPL2|TPL1
TPL2|TPL2|TPL2
TPL2|TPL2|TPL2|TPL1|TPL1
TPL2|TPL1|TPL3|TPL2|TPL2|TPL1|TPL1|TPL3|TPL3
TPL1|TPL1|TPL2|TPL2|TPL2|TPL3|TPL3|TPL3|TPL3|TPL1|TPL1
TPL1|TPL1|TPL1|TPL2|TPL2|TPL2|TPL3|TPL3|TPL3|TPL4|TPL4|TPL4|TPL5|TPL5|TPL5|TPL6|TPL6|TPL6
TPL1|TPL6|TPL1|TPL2|TPL2|TPL5|TPL2|TPL3|TPL1|TPL3|TPL4|TPL4|TPL5|TPL3|TPL5|TPL6|TPL4|TPL6';
$subst = "$1$2$3$4$5$6";
$result = preg_replace($re, $subst, $str);
echo "The result of the substitution is ".$result;
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for PHP, please visit: http://php.net/manual/en/ref.pcre.php