Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums Back End PHP arrays

  • This topic is empty.
Viewing 9 posts - 1 through 9 (of 9 total)
  • Author
    Posts
  • #31562
    jamygolden
    Member

    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?

    #61915
    Sirlon
    Member

    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.

    #61889
    Keyamoon
    Member

    I would use regular expressions to achieve this:

    preg_replace('/s(w+)$/i', ' $1', 'this is a sample sentence');
    #61808
    jamygolden
    Member

    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 =)

    #61809
    Sirlon
    Member

    ups typo, i meant strrpos . ^^

    #61697
    noahgelman
    Participant

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

    #61698
    jamygolden
    Member
    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.

    https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/regexp

    #61655
    Sirlon
    Member

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

    #61455
    jamygolden
    Member

    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.

    /s(S+)$/i

Viewing 9 posts - 1 through 9 (of 9 total)
  • The forum ‘Back End’ is closed to new topics and replies.