http://qs1969.pair.com?node_id=147893

emcb has asked for the wisdom of the Perl Monks concerning the following question:

Hi,

I have written a sub called str_replace. This sub is supposed to work the same as the php function str_replace. Heres the code:

sub str_replace
{
  my( $find,$replace,$what ) = @_;
  $what =~ s/$find/$replace/i;
  return $what;
}

I then use this function to find x and replace it with y in z like so:

$string = str_replace("Hi", "Hello", "Hello My Name Is Elfyn");

This function only returns 'Hi' instead of 'Hi My name Is Elfyn'. Any help on why fellow monks.

Cheers,

Elfyn

Replies are listed 'Best First'.
Re: dodgy sub
by broquaint (Abbot) on Feb 27, 2002 at 13:42 UTC
    Try switching your parameters
    print str_replace("Hello", "Hi", "Hello My Name Is Elfyn\n");
    Also, since your implmentation of PHP's str_replace doesn't take 'mixed' value types (i.e strings, arrays, references etc), it's only a partial implmentation.
    HTH

    broquaint

Re: dodgy sub
by strat (Canon) on Feb 27, 2002 at 13:43 UTC
    maybe you could try swapping hello and hi?
    $string = str_replace("Hello", "Hi", "Hello My Name Is Elfyn");
    Besides, if there are strange chars in $find ( \, +, *, (, [ or the like), better write:
    $what =~ s/\Q$find/$replace/;
    Otherwise, you may get nasty errors

    Best regards,
    perl -le "s==*F=e=>y~\*martinF~stronat~=>s~[^\w]~~g=>chop,print"

Re: dodgy sub
by dragonchild (Archbishop) on Feb 27, 2002 at 14:55 UTC
    Just so you're aware, you can do something like
    $string = str_replace(qr/(?:Hello)|(?:Hi)/, "Good-bye", "Hello My Name + is Elfyn");
    qr creates something that allows you to embed regex operators within a string to be used in a regex. :-)

    ------
    We are the carpenters and bricklayers of the Information Age.

    Don't go borrowing trouble. For programmers, this means Worry only about what you need to implement.

      Thanks oh worthy monks.

      Im still learning regexps, and i thought my code was wrong. Oh it is :)

      Elfyn