- This topic is empty.
-
AuthorPosts
-
February 9, 2011 at 5:51 am #31562jamygoldenMember
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 #61915SirlonMemberI’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 #61889KeyamoonMemberI 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 #61808jamygoldenMemberFebruary 9, 2011 at 9:11 am #61809SirlonMemberups typo, i meant strrpos . ^^
February 9, 2011 at 12:48 pm #61697noahgelmanParticipantCan you walk me through what Keyamoon’s code does? My php isn’t up to snuff either
February 9, 2011 at 1:58 pm #61698jamygoldenMemberpreg_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
February 9, 2011 at 2:17 pm #61655SirlonMemberYou can also do /s([^s]+)$/gi
February 10, 2011 at 2:43 am #61455jamygoldenMemberYeah 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
-
AuthorPosts
- The forum ‘Back End’ is closed to new topics and replies.