Give help. Get help.

  • # February 9, 2011 at 5:51 am

    My knowledge is not up to scratch when it comes to arrays.

    What I want to do, is take a sentence string and put a non-breaking-space between the 2nd last word and the last word. for example.

    This is an example sentence.

    Would be come

    This is an example sentence.

    What I was thinking was explode() the string, echo the array except for the 2nd last and last item. I’m not sure how to do that though, or even if it’s the most effective way of doing this.

    Any ideas?

    # February 9, 2011 at 6:33 am

    I’m not that expert in php but you can do a str_replace.

    or (i hate regular expressions ;) )

    $s = "This is an example sentence.";
    $s = substr_replace($s," ",strpos($s, " "), 1);

    Not testet.

    # February 9, 2011 at 7:07 am

    I would use regular expressions to achieve this:

    preg_replace('/s(w+)$/i', ' $1', 'this is a sample sentence');
    # February 9, 2011 at 8:50 am

    Thanks a lot both of you.

    @Sirlon your solution puts a non-breaking-space between the first and second word, not the last and second last.

    @Keyamoon yours works perfectly =)

    # February 9, 2011 at 9:11 am

    ups typo, i meant strrpos . ^^

    # February 9, 2011 at 12:48 pm

    Can you walk me through what Keyamoon’s code does? My php isn’t up to snuff either

    # February 9, 2011 at 1:58 pm
    preg_replace('/s(w+)$/i', ' $1', 'this is a sample sentence');

    I’ve got most of this: /s(w+)$/i
    s (Match a space character)
    w (match an alpha numeric character) + (keep matching this until fail. Aka the space)
    $ (the matched characters should end with (w+)

    So it matches a space character followed by (and ending with) a string of alpha numeric characters. I’m not exactly sure what the i means, but I’m sure it must have something to do with the fact that it has matched the very last possible match.

     $1 replaces the matched characters in the brackets with a non-breaking-space followed by the matched characters.

    Please correct me if I’m wrong.

    # February 9, 2011 at 2:17 pm

    You can also do /s([^s]+)$/gi

    # February 10, 2011 at 2:43 am

    Yeah you’re right @Sirlon, (The added g gives errors though) that actually works better since it gets the punctuation marks too.

    I’ve managed to optimize it even more :p
    S does the same thing as [^s]
    For those of you who don’t know, it matches any single character NON-space.


Viewing 9 posts - 1 through 9 (of 9 total)

You must be logged in to reply to this topic.