Jump to content
xisto Community
Sign in to follow this  
martvefun

Str_replace() Not Every Occurence

Recommended Posts

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

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 variable

For example, aa_bb_$replace_h

And do

str_replace  ( '_$replace_'  , '-$replace-'  ,  'ab_cd_$replace_h')

Share this post


Link to post
Share on other sites

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

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 by martvefun (see edit history)

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×
×
  • Create New...

Important Information

Terms of Use | Privacy Policy | Guidelines | We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.