martvefun 0 Report post Posted March 8, 2010 Hello,I've a string like "ab_cd_efg_h" and I want to change it into "ab_cd-efg-h"I know the function str_replace ( '_' , '-' , 'ab_cd_efg_h') but it changes every occurrence of '_'how can I specify to change one particular occurrence (just knowing its occurrence position, not the exact char number)thank you Share this post Link to post Share on other sites
martvefun 0 Report post Posted March 9, 2010 ok I've found a way of doing it $str='ab_cd_efg_h'$end = str_replace('_', '-', $str);$end = preg_replace('/-/', '_', $end, 1); if someone has a better way... Share this post Link to post Share on other sites
BuffaloHelp 24 Report post Posted March 9, 2010 I think you should find out the pattern in the sequence.Does "efg" appear every second "_"?Does "efg" appear in 3, where other groups are 2 or less, i.e. aa_bb_efg_h or aaaa_b_efg_h?Does "efg" appear as 3rd, whatever the string legth be, i.e. aa_bb_efg_hh_ii_jj or aaa_bbb_efg_hhh_iii_jjj_kkk?You can even go before the string is formed, i.e. if "efg" is part of input from multiple places, isolate when "efg" is entered and assign a different variableFor example, aa_bb_$replace_hAnd do str_replace ( '_$replace_' , '-$replace-' , 'ab_cd_$replace_h') Share this post Link to post Share on other sites
truefusion 3 Report post Posted March 9, 2010 how can I specify to change one particular occurrence (just knowing its occurrence position, not the exact char number)Just use substr_replace() in combination with strpos() (unless you already know the exact position, then you can skip strpos()). Share this post Link to post Share on other sites
martvefun 0 Report post Posted March 9, 2010 (edited) the string I gave was just an exempleI know that between the two first words (don't know the length), I should have _ and - between all the following (don't know how many and where)I can have ab_cd_efg_h as well than 123_4_56@truefusion : your solution seems good Edited March 9, 2010 by martvefun (see edit history) Share this post Link to post Share on other sites