Php replace string

Discussion in 'PHP' started by Nithya_hiox, Sep 27, 2010.

  1. #1
    Hi All,
    I am a new bie to PHP.

    I have to extract a mail containing text and images. I have to replace the existing image src with new image source.
    When I use preg_replace all images sources got replaced with a single image.

    But I need to replace every image src with corresponding new image source. Could anyone plz help me
     
    Nithya_hiox, Sep 27, 2010 IP
  2. HungryMinds

    HungryMinds Active Member

    Messages:
    216
    Likes Received:
    2
    Best Answers:
    1
    Trophy Points:
    63
    #2
    Hi!

    Try:

    
    <?php
    $String = "I Like Apple.";
    
    // Find "Apple"
    $New = "Apple";
    
    // Replace To "Banana"
    $Replace = "Banana";
    
    $Result = str_replace($New, $Replace, $Srting);
    print $Result;
    ?>
    
    Code (markup):
     
    HungryMinds, Sep 27, 2010 IP
  3. Nithya_hiox

    Nithya_hiox Peon

    Messages:
    12
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3



    Hi,

    Thanks for your reply.

    $New = "Apple is the best. Apple is sweet";

    $Replace = "Banana";
    $Replace1 = "Orange";

    In the above example , I have to replace Apple of the first occurence with Banana and second occurence with Orange. In this case, when I use str_replace both the "Apple" in the sentence get replaced with a single string.

    How could I overcome this? Do I have to use any other function?
     
    Nithya_hiox, Sep 27, 2010 IP
  4. HungryMinds

    HungryMinds Active Member

    Messages:
    216
    Likes Received:
    2
    Best Answers:
    1
    Trophy Points:
    63
    #4
    Hi!

    It's Quite Difficult My Friend...

    Click Here To Preview

    Try This Example:

    
    <?php
    
    // Array
    // Every Array Of "$Find" Will Be Replaced Into Every Array Of "$Replace" From Top To Bottom.
    
    $Find = array	(
    				"black.jpg",
    				"red.jpg"
    				);
    				
    $Replace = array(
    				"blue.jpg",
    				"yellow.jpg"
    				);
    
    print "Before Replacing, Image 1: <img src='images/black.jpg'> And Image 2: <img src='images/red.jpg'>";
    print "<br />";
    $Content = "After Replacing, Image 1: <img src='images/black.jpg'> And Image 2: <img src='images/red.jpg'>";
    $Result = str_replace($Find, $Replace, $Content);
    print $Result;
    
    ?>
    
    Code (markup):
     
    HungryMinds, Sep 27, 2010 IP