简体   繁体   中英

Having trouble removing part of a string

Given the string "123456789@test.com", I'm trying to remove from the '@' symbol on, I just want the numbers. I've been trying to split the string into an array and remove array elements based on if that element is numeric, then merging the elements back into a string. My code...

$employee_id = "123456789@test.com";
$employee_id_array = str_split($employee_id);

for($i = 0; $i < sizeof($employee_id_array); $i++) {
    if(is_numeric($employee_id_array[$i]) === false) {
        unset($employee_id_array[$i]);
        $employee_id_array = array_values($employee_id_array);
    }
}

$employee_id = implode($employee_id_array);

echo "employee id: $employee_id";

What it should print out: 123456789

What it actually prints out: 123456789ts.o

What am I missing?

echo strstr($employee_id, '@', true);

To get all the numbers in employee_id string:

$employee_id = "123456789@test.com";
preg_match_all('!\d+!', $employee_id, $matches);
echo $matches[0][0];

This will return all the numbers in the provided string.

If you want to get string before @ in employee_id then you can try this:

$employee_id = "123456789@test.com";
$output = explode('@', $employee_id);
echo $output[0];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM