Steven
Steven

Reputation: 13985

PHP string remove everything but center numbers?

I have a string "Mod. 816-10 025" and I want to remove everything but the 816-10.

Conditions:

Can someone help me? I've tried like 5 different regex but no success.

Upvotes: 0

Views: 324

Answers (5)

ssice
ssice

Reputation: 3683

People are posting about preg_replace answers but none of them are taking care of any whitepace except an space. If you prefer preg_replace() to preg_match(), I'd rather use

preg_replace('/.*\s+(\d+-\d+)\s+.*/', '$1', $input);

Upvotes: 0

Joe
Joe

Reputation: 1057

$foo = "Mod. 816-10 025";
$bar = explode(" ", $foo);
$result = $bar[1];

all these answers could be right, its just a matter of what exactly you where looking for.

Upvotes: 0

amosrivera
amosrivera

Reputation: 26514

If the conditions always remain, there is no need for RegEx:

$string = explode(" ","Mod. 816-10 025");
$number = $string[1];

Note: Using php native functions will usually be faster than the powerful RegEx.

Upvotes: 1

ssice
ssice

Reputation: 3683

<?php
# ...
$pattern = '/\d+-\d+/';
$matches = array();
preg_match($pattern, $input, $matches);

Now $matches[0] will have you NUM-NUM string. If you want to limit the size of the numbers (if it were between 2 and 3 digits all the time, the pattern could be something like /\d{2,3}-\d{2,3}/

Upvotes: 1

Czechnology
Czechnology

Reputation: 14992

$text = "Mod. 816-10 025";
echo preg_replace('~.+ (\d+-\d+) .+~', '\1', $text);
// prints: 816-10

Upvotes: 1

Related Questions