Jump to content

Abbreviate First name using regex


ianco

Recommended Posts

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


 

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.