$re = '/(\d)(?=\d*:)(?=.{6}(\d)\d*~.*?(\1;.*?\2_(\d)|\2;.*?\1_(\d)))|(\d)(?=\d*~)(?<=(\d)..{6})(?=\d*~.*?(\6;.*?\7_.*?(!|;)|\7;.*?\6_.*?(!|;)))(?=\d*~.*~.*?(\9(.)|\10(.)))|~.*?~.*?~/';
$str = '382829:239091~0;0_01_12_23_34_45_56_67_78_89_9!1;1_22_33_44_55_66_77_88_9!9_02;2_43_54_65_76_87_9!8_09_13;3_64_75_86_9!7_08_19_24;4_85_9!6_07_18_29_35;5_06_17_28_39_46;6_27_38_49_57;7_48_59_68;8_69_79;9_8~!0;1~~01234567890';
$subst = "$4$5$12$13";
$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