SitePoint Sponsor

User Tag List

Results 1 to 6 of 6
  1. #1
    SitePoint Enthusiast Fender963's Avatar
    Join Date
    Dec 2003
    Location
    Texas
    Posts
    95
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Split variable apart

    I'm having trouble figuring out how to do something. Say I have:
    $word = "hello world my name is bob";

    I need to split it apart by word, check to see if the word is 3 characters or less, if it is add a * to the end and then join it all back together. So:
    Before
    $word = "hello world my name is bob"

    After
    $word = "hello world my* name is* bob*"

    Any ideas?

    Thank you,
    Kyle

  2. #2
    . shoooo... silver trophy logic_earth's Avatar
    Join Date
    Oct 2005
    Location
    CA
    Posts
    9,013
    Mentioned
    8 Post(s)
    Tagged
    0 Thread(s)
    PHP Code:
     $string 'hello world my name is bob';
     
    $_string explode(' ',$_string);
     
    $o_string '';
     foreach(
    $string as $k => $v){
         if(
    strlen($v) >= 3){$v .= '*';}
         
    $o_string .= $v;
     }
     
     
    $string $o_string
    Logic without the fatal effects.
    All code snippets are licensed under WTFPL.


  3. #3
    SitePoint Enthusiast Fender963's Avatar
    Join Date
    Dec 2003
    Location
    Texas
    Posts
    95
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hey Logic_earth,

    I get this error Invalid argument supplied for foreach()

    Thank you for teh help.

  4. #4
    . shoooo... silver trophy logic_earth's Avatar
    Join Date
    Oct 2005
    Location
    CA
    Posts
    9,013
    Mentioned
    8 Post(s)
    Tagged
    0 Thread(s)
    oh i made a mistake...

    change the explode to:
    PHP Code:
    $_string explode(' ',$string); 
    and change the foreach to this:
    PHP Code:
    foreach($_string as $k => $v){ 
    Logic without the fatal effects.
    All code snippets are licensed under WTFPL.


  5. #5
    SitePoint Enthusiast Fender963's Avatar
    Join Date
    Dec 2003
    Location
    Texas
    Posts
    95
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Great works like a charm thank you!

  6. #6
    eschew sesquipedalians silver trophy sweatje's Avatar
    Join Date
    Jun 2003
    Location
    Iowa, USA
    Posts
    3,749
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    or shorter:
    PHP Code:
    $str "hello world my name is bob"
    $a explode(" ",$str); 
    array_walk($acreate_function('&$in','if (strlen($in) <= 3) $in .= "*";')); 
    echo 
    implode(" ",$a); 
    Jason Sweat ZCE - jsweat_php@yahoo.com
    Book: PHP Patterns
    Good Stuff: SimpleTest PHPUnit FireFox ADOdb YUI
    Detestable (adjective): software that isn't testable.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •