提取PHP中的字符串


Extract the strings in PHP

我是正则表达式的新手。

我得到的字符串像:

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

有谁能告诉我正则表达式和如何使用它的函数吗?

试试这个:

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

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

感谢你们的尝试,我已经使用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;
    }

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

$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
^(?:(?!'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)

只要' 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);
});