ianco Posted March 30, 2010 Share Posted March 30, 2010 Hi I'm looking to do a form where the first name is abbreviated in the output. I can't seem to find a solution and what i have so far is not working. Any ideas where i'm going wrong or if it's even possible? Thanks Ian $name = $_POST["name"]; $find ="/^\;\s[A-Z]{1}[a-z]+\s$/"; $replace = "/^\;\s[a-z]{1}\.\s$/"; echo preg_replace($find,$replace,$name); Quote Link to comment https://forums.phpfreaks.com/topic/197024-abbreviate-first-name-using-regex/ Share on other sites More sharing options...
Psycho Posted April 2, 2010 Share Posted April 2, 2010 Hmm... are you talking about abbreviating a person's name? If so, you aren't going to be able to do this with RegEx. You would need to build a library/table of names and their applicable abbreviations. The abbreviations for many/most names cannot be determined programatically: Michael = Mike Robert = Bob Anthony = Tony etc. Quote Link to comment https://forums.phpfreaks.com/topic/197024-abbreviate-first-name-using-regex/#findComment-1035731 Share on other sites More sharing options...
ianco Posted April 2, 2010 Author Share Posted April 2, 2010 what i wanted was Micheal Smith -> M. Smith in a list of names separated by a semicolon It would be too much hassle if i had to use a str_replace() for every name possible Quote Link to comment https://forums.phpfreaks.com/topic/197024-abbreviate-first-name-using-regex/#findComment-1035818 Share on other sites More sharing options...
salathe Posted April 2, 2010 Share Posted April 2, 2010 Here's an example which takes a "comma-space" separated list of names and abbreviates the first name (of each name). It might not be perfect for your own script but might provide an idea of how to go about something like this; there are lots of other ways, some simpler and some more complex but this is the regex forum so lets give you some regex. $names = 'Jack Smith; Oliver Brown; Charlie Wilson; Harry Robertson'; echo preg_replace('/(?<=^|;\s)([A-Z])\S+/', '$1.', $names); // J. Smith; O. Brown; C. Wilson; H. Robertson The main point to take away from the example above is the use of a negative lookbehind to make sure we capture the capital letter either at the very start of the string (the very first first name) or after a comma-space (every other first name). The rest of the pattern is just a basic way to get the whole of the first name, capturing the first letter for use in the replacement. Quote Link to comment https://forums.phpfreaks.com/topic/197024-abbreviate-first-name-using-regex/#findComment-1035860 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.