开发者

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:

  • The number in the center will always be ###-##
  • It may not be 3 numbers - 2 numbers but it will always be space numbers dash numbers space

Can someone help开发者_运维技巧 me? I've tried like 5 different regex but no success.


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.


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


<?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}/


$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.


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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜