ReynierPM ReynierPM - 3 months ago 9
PHP Question

How to get the string before "_" in PHP

I need to get the string before

_
, but what I've tried is not working properly. The following is a list of input values stored in
$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


This is what I have tried:

$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;
}


The code works almost perfectly, but for those, where you have not the ending
_N
it fails, because it is removing part of the original string (see the output below).

vendor
vendor
hotel_name
hotel_room_type
hotel_in_date


A valid output should be as follow:

vendor_code
vendor_name
hotel_name
hotel_room_type
hotel_in_date


This means, I need to remove all the content after the last
_N
.

Can any give me some advice here?

Answer

Just remove the ending part _N(if occurs) using preg_replace function:

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