Zabs
Zabs

Reputation: 14142

PHP Regular Expression to remove everything after an underscore

I have an array that contains a number of strings in two formats, these are..

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

I need to generate a regular expression to remove the underscore and any characters after this, so 65_12345 would become 65, Can anyone suggest a simple expression to do this?

Upvotes: 3

Views: 1223

Answers (4)

Why use a regex? The function strstr can do this easily:

$num = '65_12345';
echo strstr($num, '_', true); // 65

For replacing an array of numbers, all having the same format:

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

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

print_r($numArr);

Output:

Array
(
    [0] => 65
    [1] => 223
    [2] => 5334
)

Upvotes: 5

Lakatos Gyula
Lakatos Gyula

Reputation: 4160

This can do what you want, but why regex?

#_.*#

A fast version:

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

Upvotes: 3

Sabuj Hassan
Sabuj Hassan

Reputation: 39365

If regex:

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

_.* means anything after underscore with the underscore.

Upvotes: 2

Nambi
Nambi

Reputation: 12042

Use the preg_replace for the regex way

echo  preg_replace('~(\d+)_\d+~',"$1",'65_12345');

Use explode for non-regex way

echo explode('_','65_12345')[0];

Upvotes: 5

Related Questions