Looking for a small php function

Discussion in 'PHP' started by ruud, Jul 30, 2007.

  1. #1
    I'm looking a function like this;

    our_function("word1 word2");

    result : "word1+word2"

    Thanks.
     
    ruud, Jul 30, 2007 IP
  2. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #2
    So you want to replace spaces with plus signs?
    
    $text = preg_replace('/\s+/', '+', $text);
    
    PHP:
     
    nico_swd, Jul 30, 2007 IP
    ruud likes this.
  3. ruud

    ruud Peon

    Messages:
    308
    Likes Received:
    16
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Yes, this is. worked. thanks.

    Rep added.
     
    ruud, Jul 30, 2007 IP
  4. wmtips

    wmtips Well-Known Member

    Messages:
    601
    Likes Received:
    70
    Best Answers:
    1
    Trophy Points:
    150
    #4
    I would recommend str_replace for such a simple operation. It has simplier functionality, bit it is much faster than preg_replace:

    
    $text = str_replace(' ', '+', $text);
    
    PHP:
     
    wmtips, Jul 30, 2007 IP
  5. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #5
    I'm well aware of that (and I was almost sire someone would pick up on that), but I decided to use preg_replace() to replace multiple spaces with just one plus sign.
     
    nico_swd, Jul 30, 2007 IP
  6. wmtips

    wmtips Well-Known Member

    Messages:
    601
    Likes Received:
    70
    Best Answers:
    1
    Trophy Points:
    150
    #6
    nico, I understand your point, it's OK, it depends on what he needs. I've just provided another solution for his task.

    About multiple spaces: it seems he needs to encode urls (' ' => '+', '&' => '%26' etc.) so the best solution for that should be
    
    $text = urlencode($text);
    
    PHP:
     
    wmtips, Jul 30, 2007 IP
  7. ablaye

    ablaye Well-Known Member

    Messages:
    4,024
    Likes Received:
    97
    Best Answers:
    0
    Trophy Points:
    150
    #7
    Wow. That's pretty smart. I am very impressed.
     
    ablaye, Jul 30, 2007 IP