ExpressionEngine CMS
Open, Free, Amazing

Thread

This is an archived forum and the content is probably no longer relevant, but is provided here for posterity.

The active forums are here.

[string manip Q] splitting string on 2nd space

January 10, 2010 12:26am

Subscribe [3]
  • #1 / Jan 10, 2010 12:26am

    brianw1975

    257 posts

    Ok guys and gals i’ve been suffering code-block for the past couple of hours on this thing.

    I’m trying to generate some graphics via php based on fields in a database (there are roughly 1500 pictures that need to be created - so not doing them in Photoshop)

    Anyhoo…

    I’ve got a string “10¢ OFF Regular Price”

    How can I split that at the second space?  so that i get

    $str[1] = "10¢ OFF";
    $str[2] = "Regular Price";

    Like I said, been blocked for hours on this stupid but of junk, hoping someone can help me out.

    TIA.

  • #2 / Jan 10, 2010 3:25am

    brianw1975

    257 posts

    ah, yes, that would be a way.. however, as I said I have 1500 records that need to be parsed.  So, while yeah, that is a solution I was hoping for a suggestion that was a bit more robust, but… I may just have to use a hammer to nail and do a switch statement based on the size of the array generated from the explode and then concatenate those results… I could also customize it based on the length of the words as well…

    Thanks for the suggestion.

    Here are some other examples.

    ex:

    Beef
    Beef Stew
    Excellent For Broiling
    Hamburger from Ground Chuck
    Fully Cooked - Ready to eat
    Compre 1 y Gratis 1
    Reduced! use today or freeze

  • #3 / Jan 10, 2010 3:29am

    Dyllon

    92 posts

    Use explode(), then re-assemble as needed:

    <?php
    
    $foo = "Hello world. It's a beautiful day.";
    $bar = explode(" ",$str));
    echo $bar[0] . $bar[1];
    ?>

    Untested.

    Use the limit parameter of explode to make it easier to re-assemble.

    $str = "10¢ OFF Regular Price";
    $arr = explode(' ', $str, 3);
    $arr[1] = $arr[0] . ' ' . $arr[1];
    array_shift($arr);
    
    print_r($arr);

    Result:

    Array
    (
        [0] => 10¢ OFF
        [1] => Regular Price
    )
  • #4 / Jan 10, 2010 4:06am

    Colin Williams

    2601 posts

    You could use regex assertions to say, “find first space preceded by a space” but I’m not sure it would be any more or less efficient than what’s been suggested so far.

.(JavaScript must be enabled to view this email address)

ExpressionEngine News!

#eecms, #events, #releases