在PHP中提取字符串

在PHP中提取字符串,php,regex,preg-match,preg-split,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 我需要通过排除非x来提取包含非x的少数字符串,这意味着输出字符串应该如下所示: DFE2001 NE CAT11004 TP FFE2001 NE AVI2002 NE LAB4000 SU BA-PRI008 FDD2001

我不熟悉正则表达式

我有这样的字符串:

DFE2001 NE Not 1
CAT11004 TP
FFE2001 NE Not 3
AVI2002 NE
LAB4000 SU
BA-PRI008 Not 1
FDD2001 NE Not 2
我需要通过排除
非x
来提取包含
非x
的少数字符串,这意味着输出字符串应该如下所示:

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

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

谢谢大家的尝试,我已经使用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;
    }
$mystring='DFE2001 NE非1';
//$mystring='LAB4000 SU';
$findme='Not';
$pos=strpos($mystring,$findme);
//注意我们使用的===。Simply==无法按预期工作
//因为“a”的位置是第0个(第一个)字符。
如果($pos==false){
echo“在字符串“$mystring”中未找到字符串“$findme”;
$mystring=$mystring;
echo'
mystring::'。$mystring; }否则{ echo“在字符串“$mystring”中找到了字符串“$findme”; echo“并存在于位置$pos”; $mystring=substr($mystring,0,$pos); echo'
mystring::'。$mystring; }
试试这个:

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

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

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

$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
$re=“/。+?(?=非)/”;//reg用于检查字符串是否有错误
$str=“DFE2001 NE非1”;
预匹配($re,$str,$matches);
回声';打印($matches);//先把绳子拿出来,再不穿
你可以试试这个。看演示


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


谢谢@TareqMahmood:一行代码。工作很有魅力。非常感谢。谢谢大家。这不是在1之前删除空格。你能告诉我如何在1之前删除1个空格吗?你能在答案中检查我的最新编辑吗?我猜你还在用我写的第一本。请确认。这也有效。preg_replace('/Not\d$/','$mystring)。感谢您尝试此
/\s*而不是[\d\s\w]*$/
^(?:(?!\bNot\b).)*(?=\s+|$)
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)
$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);
});