正则表达式帮助。字符串没有空格,但中心有5位数字。仅提取数字。 PHP

时间:2013-01-07 23:35:46

标签: php regex

示例字符串

Rpt#_SPACE_MINVTAN<br_SPACE_/> _SPACE__SPACE__SPACE__SPACE__SPACE_01212_SPACE__SPACE_

第一行末尾有换行符。第二行总是有5个空格,然后是5位数字,然后是两个空格....现在在我粘贴之前有更多随机文本,之后更随机。

客户编号后的_SPACE_数必须为2或更多。

我想我正在寻找的是:

在大字符串_SPACE__SPACE__SPACE__SPACE__SPACE_012345_SPACE__SPACE_

的中间查找

将数字提取到变量中。

4 个答案:

答案 0 :(得分:1)

针对特定字符串类型的另一种解决方案:

$string = "Rpt#_SPACE_MINVTAN<br_SPACE_/>_SPACE__SPACE__SPACE__SPACE__SPACE_01212_SPACE__SPACE_";

我已对此进行了测试,确实有效。

<?php
$text = "Rpt#_SPACE_MINVTAN<br_SPACE_/>_SPACE__SPACE__SPACE__SPACE__SPACE_01212_SPACE__SPACE_";
$text_array = explode("<br_SPACE_/>", $text);
$array1 = explode("_SPACE_", $text_array[0]);
echo $array1[0] . ' and ' . $array1[1];
$number = trim($text_array[1], "__SPACE__");
echo '<br>and ' . $number;
?>

$array1[0] is the 'Rpt#'
$array1[1] is the 'MINVTAN'
$number is '01212'

将此代码放入您的文件并看到它有效后,请记得将其作为解决方案进行检查,以便其他人知道该帖子已得到解答。如果您有任何其他问题,请随时提出;祝你有愉快的一天。

答案 1 :(得分:0)

如果您想要更具体的解决方案,请发布更具体的代码或信息。

但一种解决方案可能是:

<?php
$trimmed_text = trim($text, "__SPACE__");
?>

答案 2 :(得分:0)

对于下面的字符串,中间有5位数字,周围有空格,

_SPACE__SPACE__SPACE__SPACE__SPACE_012345_SPACE__SPACE_

您可以使用preg_match(),如下所示:

$string='_SPACE_SPACE....'; //your string here

preg_match('/\s*(\d{5})\s*/',$string,$matches);

print_r($matches); //$matches[1] will have the matched digits

编辑:

根据OP,如果文本实际上是SPACE_,则代码如下:

$string='_SPACE__SPACE__SPACE__SPACE__SPACE_12345_SPACE__SPACE_'; //your string here

preg_match('/[SPACE_]*(\d{5})[SPACE_]*/',$string,$matches);

print_r($matches); //$matches[1] will have the matched digits

答案 3 :(得分:0)

这太丑了:

function onlyNumber($str) { 
     $numbers = array(0,1,2,3,4,5,6,7,8,9);
     $icky = array('_','-','#','<','>','/');
     $num = "";
     for($i=0;$i<strlen($str);$i++) { 
            if(!ctype_alpha($str[$i]) && !in_array($str[$i],$icky) && in_array(intval($str[$i]),$numbers,true)) { 
                $num .= $str[$i];
            }
     }
     return trim($num);
}