Strip Twitter Username from Profile Field with URL and Save to New Profile Field

You need to do this in steps:

  1. Decide when you are going to parse the user’s meta to change the value.
  2. Define a function to do that.
  3. Hook that function to the appropriate action.

The original answer defined what you need to do for step #2, using preg_match() to parse the Twitter URL and extract the username.

function update_the_user( $user ) {
    // grab the twitter URL, I've used some of the code further up in your question to do this
    $twitter_url = esc_attr( get_the_author_meta( 'twitter', $user->ID ) );

    // pass it into a regular expression, and get the result
    $result = preg_match("/https?:\/\/(www\.)?twitter\.com\/(#!\/)?@?([^\/]*)/", $twitter_url, $matches);

    $twitter_username="default value";

    // if the Regex worked, the $result is now equal to 1
    if($result == 1){
        // it worked! According to the answer in the question you linked to, the $matches array will contain the username in the 3rd position
        $twitter_username = $matches[3];
    } else {
        // failure!! The regex did not find the username, abort!!!

    // The twitter username is now inside $twitter_username

    // lets add the extracted value to the users meta as 'twitter_username'
    update_user_meta( $user->ID, 'twitter_username', $twitter_username );

You’re left deciding when to handle steps 1 and 3.

When to Process the Data

This is entirely an architectural question for you, not for the site. You can process the user when their profile page is edited, when the user is viewed on the front end, or just in a bulk process and handle all users at once. It really depends on your objectives:

Hook to Appropriate Action

Once you’ve decided when to hook the function, you just tie it in.

If you want to process users when a profile page is loaded, you can hook on to personal_options:

add_action( 'personal_options', 'update_the_user' );

This action passes in a variable, $profileuser, that is populated based on the ID of the user who’s profile is open. Use this method, and you can manually load the profile pages for all of your users one at a time to update them.

Alternatively, you can run this function once against all of your users.

function update_all_users() {
    $users = get_users();

    foreach ( $users as $user ) {
        update_the_user( $user );

Just hook this function to init or some other loading action, load the site once, and let things flow.

At the end of the day …

… when you implement this code, where you implement it, and how you implement it is not up to us. You’ve asked for advice on how you can read out a Twitter URL, parse it, extract the Twitter username, and store it in meta for the user. We’ve given you that. Actually implementing any and all of the code above is an exercise you’ll need to do on your own.