1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

str_replace

Discussion in 'PHP' started by baris22, Nov 2, 2008.

  1. #1
    I want to find and replace some words. the problem is i do not want to replace the words if they are in a word.

    forexample this is the sentence:

    
    I want to change.
    
    PHP:
    the output should be:

    
    I want change.
    
    PHP:
    as you see "an" did not changed in the word "change"
    because "an" is not by it self.

    
    
    $short = array('of', 'to', 'in', 'an');
    $title = str_replace($short, "", $title);
    
    
    PHP:
    How can i do this?

    Thanks
     
    baris22, Nov 2, 2008 IP
  2. joebert

    joebert Well-Known Member

    Messages:
    2,150
    Likes Received:
    88
    Best Answers:
    0
    Trophy Points:
    145
    #2
    Use preg_replace instead of str_replace so that you can utilize the word-boundry character.

    $short = array('of', 'to', 'in', 'an');
    $pattern = '#\b' . implode('\b|\b', $short) . '\b#i';
    $title = preg_replace($pattern, '', $title);
    Code (markup):
     
    joebert, Nov 2, 2008 IP
  3. rohan_shenoy

    rohan_shenoy Active Member

    Messages:
    441
    Likes Received:
    20
    Best Answers:
    0
    Trophy Points:
    60
    #3
    
    <?php
    $subject='I want an anaconda';
    $search=' an ';//observe the leading and traliing whitespaces around 'an'
    $replace=' ';//replace it with a white-space
    $subject=str_replace($search,$replace,$subject);
    echo $subject;//I want anaconda
    //you may have a $search array to look for other possible situations where you may have that word.
    ?>
    
    PHP:
     
    rohan_shenoy, Nov 2, 2008 IP
  4. joebert

    joebert Well-Known Member

    Messages:
    2,150
    Likes Received:
    88
    Best Answers:
    0
    Trophy Points:
    145
    #4
    Which completely falls apart with

    Seriously, don't fumble around with str_replace, let the computer do the work for you and use preg_replace.
     
    joebert, Nov 2, 2008 IP
  5. rohan_shenoy

    rohan_shenoy Active Member

    Messages:
    441
    Likes Received:
    20
    Best Answers:
    0
    Trophy Points:
    60
    #5
    ^^
    That is why you must read the solution completely and understand it. You missed the comment that read
    And if case is a issue. use case-insensitive replacements, str_ireplace() !
     
    rohan_shenoy, Nov 3, 2008 IP