Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

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

by kommesel (Sexton)
on Jul 20, 2001 at 13:44 UTC ( #98357=categorized question: print w/replies, xml ) Need Help??
Contributed by kommesel on Jul 20, 2001 at 13:44 UTC
Q&A  > strings


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

You can use a s/// regex like this:

my $str = "I have a dream"; my $find = "have"; my $replace = "had"; $find = quotemeta $find; # escape regex metachars if present $str =~ s/$find/$replace/g; print $str;

The quotemeta lets you find strings that contain regex meta characters and the /g at the end of the s/// does all occurances.

cheers

tachyon

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

Another way to do it is split the string at every occurrence of $find and then join it together using the new pattern $replace like this:

$string = join( $replace, split($find, $string) );
I think, this is a much neater way to do it, however I do not know how fast it is or how much more memory it uses. I have found that in JavaScript, this method works faster than the regular replace() method. Generally, working with arrays in JavaScript is always faster than working with strings. Btw could somebody do a benchmark on this to see how it compares to the other solutions?
Answer: How do I replace a substring (if exists) with a different substring in a string?
contributed by davorg

With appropriate use of index, length and substr.

And remember that substr can be used as an lvalue.

Answer: How do I replace a substring (if exists) with a different substring in a string?
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;

Please (register and) log in if you wish to add an answer



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.
  • Log In?
    Username:
    Password:

    What's my password?
    Create A New User
    Chatterbox?
    and all is quiet...

    How do I use this? | Other CB clients
    Other Users?
    Others examining the Monastery: (3)
    As of 2016-12-03 19:52 GMT
    Sections?
    Information?
    Find Nodes?
    Leftovers?
      Voting Booth?
      On a regular basis, I'm most likely to spy upon:













      Results (59 votes). Check out past polls.