简体   繁体   English

删除字符串的一部分时遇到问题

[英]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. 给定字符串“ 123456789@test.com”,我试图从'@'符号上删除,我只想要数字。 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 它应该打印出什么:123456789

What it actually prints out: 123456789ts.o 它实际打印出的内容:123456789ts.o

What am I missing? 我想念什么?

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

To get all the numbers in employee_id string: 要获取employee_id字符串中的所有数字:

$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 @之前获取字符串,则可以尝试以下操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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