如何获取PHP中“_”之前的字符串

How to get the string before "_" in PHP

我需要在 _ 之前获取字符串,但我尝试过的方法无法正常工作。以下是存储在 $b var:

中的输入值列表
vendor_code
vendor_name
hotel_name_0
hotel_room_type_0
hotel_in_date_0
...
vendor_code
vendor_name
hotel_name_N
hotel_room_type_N
hotel_in_date_N

这是我试过的:

$a = [
    'vendor_code',
    'vendor_name',
    'hotel_name_0',
    'hotel_room_type_0',
    'hotel_in_date_0'
];

foreach ($a as $b) {
    echo substr($b, 0, -(strlen(strrchr($b, '_')))), PHP_EOL;
}

该代码几乎可以完美运行,但对于那些没有结尾 _N 的代码,它会失败,因为它会删除部分原始字符串(请参阅下面的输出)。

vendor 
vendor 
hotel_name 
hotel_room_type 
hotel_in_date

一个有效的输出应该如下:

vendor_code
vendor_name
hotel_name 
hotel_room_type 
hotel_in_date

这意味着,我需要删除最后一个_N之后的所有内容。

有没有人可以给我一些建议?

试试看:

foreach ($a as $b) {
    list($first, $second) = explode('_', $b, 2);
    echo implode(' ', [$first, $second, PHP_EOL]);
}

您可以使用如下内容:

$a = [
    'vendor_code',
    'vendor_name',
    'hotel_name_0',
    'hotel_room_type_0',
    'hotel_in_date_0'
];

$data = [];

foreach($a as $key) {
    $temp = explode('_', $key);
    if (is_numeric($temp[count($temp) - 1])) {
        unset($temp[count($temp) - 1]);
        $data[] = implode('_', $temp);
    } else {
        $data[] = $key;
    }
}

var_dump($data);

结果:

array (size=5)
  0 => string 'vendor_code' (length=11)
  1 => string 'vendor_name' (length=11)
  2 => string 'hotel_name' (length=10)
  3 => string 'hotel_room_type' (length=15)
  4 => string 'hotel_in_date' (length=13)

您可以尝试以下方法:

<?php

$a = [
    'vendor_code',
    'vendor_name',
    'hotel_name_0',
    'hotel_room_type_0',
    'hotel_in_date_0'
];

foreach ($a as $b) {
    $hasMatch = preg_match('/(.*)_\d+/', $b, $matches);
    if ($hasMatch) {
        echo $matches[1] . PHP_EOL;    
    } else {
        echo $b . PHP_EOL;
    }
}

输出:

vendor_code
vendor_name
hotel_name
hotel_room_type
hotel_in_date

你可以使用正则表达式来解决这个问题:

foreach ($a as $b) {
    if(preg_match('/(.*)(?:_\d)/', $b, $match)){
        echo "'$b' is a match and should be {$match[1]}\n";
    } else {
        echo "'$b' does not need a modification\n";
    }
}

结果:

>     'vendor_code' does not need a modification
>     'vendor_name' does not need a modification
>     'hotel_name_0' is a match and should be hotel_name
>     'hotel_room_type_0' is a match and should be hotel_room_type
>     'hotel_in_date_0' is a match and should be hotel_in_date

只需使用 preg_replace 函数删除结尾部分 _N(如果出现):

...
foreach ($a as $word) {
    echo preg_replace("/_\d+$/", "", $word). PHP_EOL;
}