Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Answer: How do I replace a substring (if exists) with a different substring in a string?

by dkubb (Deacon)
on Jul 20, 2001 at 22:56 UTC ( #98499=categorized answer: print w/replies, xml ) Need Help??

Q&A > strings > How do I replace a substring (if exists) with a different substring in a string? - Answer contributed by dkubb

You can use substr, length, and index inside a while loop to do what you want:

my $string = '01234567890'; my $find = '0'; my $replace = 'a'; my $pos = index($string, $find); while($pos > -1) { substr($string, $pos, length($find), $replace); $pos = index($string, $find, $pos + length($replace)); }

IMHO you can't beat the following for readability:

$string =~ s/\Q$find\E/$replace/g;

  • Comment on Answer: How do I replace a substring (if exists) with a different substring in a string?
  • Select or Download Code
Replies are listed 'Best First'.
(dkubb) Re: (3) Answer: How do I replace a substring (if exists) with a different substring in a string?
by dkubb (Deacon) on Jul 22, 2001 at 02:00 UTC

    Note: I found a bug in my earlier answer, since I can't edit it, I am posting this follow up. If the string to replace has the substring you are trying to find, it can get into an endless loop. Here is an updated ansewer:

    my $string = '01234567890'; my $find = '0'; my $replace = 'a'; my $pos = index($string, $find); while($pos > -1) { substr($string, $pos, length($find), $replace); $pos = index($string, $find, $pos + length($replace)); }

    In this case, an s/// regex is actually 5% faster.

Re: Answer: How do I replace a substring (if exists) with a different substring in a string?
by kocetoo (Novice) on Jun 28, 2016 at 12:38 UTC
    actually you can change:
    substr( $string, $pos, $length( $find ), $replace );
    with this one:
    substr( $created, $pos, length( $find ), $replace );
    $length is not function!!!
Log In?
Username:
Password:

What's my password?
Create A New User
Chatterbox?
[Discipulus]: i dream to restart kung-fu someday: i studied only 2-3 years of win-chun, tang-lang and a bit of shaolin.. the better preparation ever!
[Discipulus]: ah and hung-har too

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (7)
As of 2017-11-22 19:30 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    In order to be able to say "I know Perl", you must have:













    Results (327 votes). Check out past polls.

    Notices?