Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/251.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP正则表达式删除下划线后的所有内容_Php_Regex_Arrays_Function - Fatal编程技术网

PHP正则表达式删除下划线后的所有内容

PHP正则表达式删除下划线后的所有内容,php,regex,arrays,function,Php,Regex,Arrays,Function,我有一个数组,它包含两种格式的字符串,它们是 'number' e.g 55 'number_number' eg 65_12345 我需要生成一个正则表达式来删除下划线和其后的任何字符,因此65_12345将变成65,有人能推荐一个简单的表达式来实现这一点吗?为什么要使用正则表达式?该功能可以轻松做到这一点: $num = '65_12345'; echo strstr($num, '_', true); // 65 用于替换具有相同格式的数字数组: $numArr = ['65_1234

我有一个数组,它包含两种格式的字符串,它们是

'number' e.g 55
'number_number' eg 65_12345

我需要生成一个正则表达式来删除下划线和其后的任何字符,因此
65_12345
将变成
65
,有人能推荐一个简单的表达式来实现这一点吗?

为什么要使用正则表达式?该功能可以轻松做到这一点:

$num = '65_12345';
echo strstr($num, '_', true); // 65
用于替换具有相同格式的数字数组:

$numArr = ['65_12345','223_43434','5334_23332'];

array_walk($numArr, function(&$v) {
    $v = strstr($v, '_', true);
});

print_r($numArr);
Array
(
    [0] => 65
    [1] => 223
    [2] => 5334
)
输出:

$numArr = ['65_12345','223_43434','5334_23332'];

array_walk($numArr, function(&$v) {
    $v = strstr($v, '_', true);
});

print_r($numArr);
Array
(
    [0] => 65
    [1] => 223
    [2] => 5334
)

将preg_replace用于regex方式

echo  preg_replace('~(\d+)_\d+~',"$1",'65_12345');
echo explode('_','65_12345')[0];
对于非正则表达式方式,使用
分解

echo  preg_replace('~(\d+)_\d+~',"$1",'65_12345');
echo explode('_','65_12345')[0];
如果是正则表达式:

$string = preg_replace("/_.*/", "", $string);

..*
表示下划线之后的任何内容加下划线。

这可以做您想做的事情,但为什么是正则表达式

#_.*#
快速版本:

substr('65_678789', 0, strpos('65_678789', '_'));

说得好。。我脑子里一直在想regexreason@Zabs,是的,对于这样小的操作,最好避免使用正则表达式:)每个人都给出了一些很好的答案,谢谢:)我使用了你答案的一个细微变化,因此接受了你的答案。