php - Inserting number after alphanumeric group not followed by numeric group -
i have string contains 1 or more alphanumerical codes (starting letter) separated underscore. codes followed index number, separated underscore.
i want insert index number (always 1) after each code not followed index.
here's sample :
one => one_1 one_tw2_tre_for => one_1_tw2_1_tre_1_for_1 one_tw2_tre_23_for => one_1_tw2_1_tre_23_for_1 one_3_tw2_4_tre_45 => one_3_tw2_4_tre_45
i can 2 calls preg_replace :
// add '_1' after each code $s = preg_replace('/[a-za-z][a-za-z0-9]+/', '$0_1', $s); // remove '_1' when followed index $s = preg_replace('/_1_([0-9]+)/', '_$1', $s);
i'm wondering if there's way 2 1 preg_replace (i tried lookahead , lookbehind, without success) or different way might faster, processor wise.
thanks ! :-)
preg_replace('/[a-za-z][a-za-z0-9]+(?!_[0-9]|[a-za-z0-9])/', '$0_1', $s);
or, more concise:
preg_replace('/[a-za-z][a-za-z0-9]+(?=_|$)(?!_[0-9])/', '$0_1', $s);
Comments
Post a Comment