用PHP提取字符串

时间:2015-12-08 16:45:46

标签: php regex preg-match preg-split

我是正则表达式的新手。

我得到的字符串如下:

DFE2001 NE Not 1
CAT11004 TP
FFE2001 NE Not 3
AVI2002 NE
LAB4000 SU
BA-PRI008 Not 1
FDD2001 NE Not 2

我需要通过排除Not x来提取包含Not x的少数字符串,这意味着输出字符串应该是这样的:

  DFE2001 NE
  CAT11004 TP
  FFE2001 NE
  AVI2002 NE
  LAB4000 SU
  BA-PRI008
  FDD2001 NE

任何人都可以告诉我正则表达式以及如何使用它的功能吗?

5 个答案:

答案 0 :(得分:2)

试试这个:

preg_replace('/\s*Not \d\s*$/', '', $string)

它将删除" Not x"从字符串末尾的周围空格(x表示任何数字字符)。

答案 1 :(得分:0)

感谢您的尝试,我已经设法使用strpos和substr函数执行此操作,如:

$mystring = 'DFE2001 NE Not 1';
// $mystring = 'LAB4000 SU';
$findme   = ' Not';
$pos = strpos($mystring, $findme);

// Note our use of ===.  Simply == would not work as expected
// because the position of 'a' was the 0th (first) character.
if ($pos === false) {
    echo "The string '$findme' was not found in the string '$mystring'";
        $mystring = $mystring;
        echo '<br/>mystring::::' . $mystring;
} else {
    echo "The string '$findme' was found in the string '$mystring'";
    echo " and exists at position $pos";
        $mystring = substr($mystring, 0, $pos);
        echo '<br/>mystring::::' . $mystring;
    }

答案 2 :(得分:0)

注意: - 这只是一个示例代码,您必须根据整个给定字符串计算自己的逻辑。

$re = "/.+?(?= Not)/";      // reg to check string having Not
$str = "DFE2001 NE Not 1"; 
preg_match($re, $str, $matches);
echo '<pre>';print_r($matches);  // take out string before Not

答案 3 :(得分:0)

^(?:(?!\bNot\b).)*(?=\s+|$)

你可以尝试一下。参见演示。

https://regex101.com/r/hE4jH0/44

import re
p = re.compile(ur'^(?:(?!\bNot\b).)*(?=\s+|$)', re.MULTILINE)
test_str = u"DFE2001 NE Not 1\nCAT11004 TP\nFFE2001 NE Not 3\nAVI2002 NE\nLAB4000 SU\nBA-PRI008 Not 1\nFDD2001 NE Not 2"

re.findall(p, test_str)

答案 4 :(得分:0)

只要' Not '后面的数字始终为一位数,您就可以仅使用substr执行此操作。

$input = array('DFE2001 NE Not 1',
    'CAT11004 TP',
    'FFE2001 NE Not 3',
    'AVI2002 NE',
    'LAB4000 SU',
    'BA-PRI008 Not 1',
    'FDD2001 NE Not 2'
);

array_walk($input, function(&$x) {
    if (substr($x, -6, -1) == ' Not ') $x = substr($x, 0, -6);
});