jtylerm
jtylerm

Reputation: 472

Having trouble removing part of a string

Given the string "[email protected]", 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 = "[email protected]";
$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?

Upvotes: 0

Views: 24

Answers (2)

Satish Saini
Satish Saini

Reputation: 2968

To get all the numbers in employee_id string:

$employee_id = "[email protected]";
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 = "[email protected]";
$output = explode('@', $employee_id);
echo $output[0];

Upvotes: 0

u_mulder
u_mulder

Reputation: 54841

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

Upvotes: 1

Related Questions