What's the best way to insert a user reference field value into the database? I use the references module. I have a custom form, into which I capture names into a user reference field via the autocomplete widget. So, on the form, if a user types Joe, the following appears in the input box:

Joe [uid: 5]


Now, I do not want to insert this into my database as it is because my 'Name' field is expecting just the uid. So I need to pass '5' to the database, not the string Joe [uid: 5].

To accomplish this, before I write my record to the database I pass the string Joe [uid: 5] through this code:

// * Search for match (integer) to regular expression and put in $integer.
preg_match_all('!\d+!', $form_state['values']['name'], $integer);

// * Return string representation of array elements.
$name_uid = implode(' ', $integer[0]);


$name_uid now contains '5' and is ready to be inserted. Is there an existing function that already does this? or does anyone have a better way?

The downside of my method is that you cannot have numbers in names, like 'Joe 2'. I've looked in user_reference.module, but it's not obvious, to me, how they do it.

Thanks
I couldn't make user_reference_autocomplete_validate() work for me so I turned my own code into a function, which now solves my numbers in names problem. I can't see why it would ever fail, but if anyone has a better solution, please let me know.

/**
 * Search for regular expression matches and return the last match.
 */

function extract_id($subject) {
    preg_match_all('!\d+!', $subject, $matches);
    return end($matches[0]);
}