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.
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.
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.
Would be come
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?
or (i hate regular expressions ;) )
Not testet.
@Sirlon your solution puts a non-breaking-space between the first and second word, not the last and second last.
@Keyamoon yours works perfectly =)
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.
$1replaces 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
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