Php 正则表达式捕获记录

Php 正则表达式捕获记录,php,regex,arrays,string,Php,Regex,Arrays,String,我需要捕获字符串的ZAMM记录。 当您有空间时,我无法捕获属于它的数据 我的字符串: $string ='ZAMM Et a est hac pid pid sit amet, lacus nisi ZPPP scelerisque sagittis montes, porttitor ut arcu ZAMM tincidunt cursus eu amet nunc ZAMM c ac nunc, et pid pellentesque amet, ZSSS m urna sceleris

我需要捕获字符串的ZAMM记录。 当您有空间时,我无法捕获属于它的数据

我的字符串:

$string ='ZAMM Et a est hac pid pid sit amet, lacus nisi
ZPPP scelerisque sagittis montes, porttitor ut arcu
ZAMM tincidunt cursus eu amet nunc
ZAMM c ac nunc, et pid pellentesque amet, 
ZSSS m urna scelerisque in vut';
预期回报:

ZAMM Et a est hac pid pid sit amet, lacus nisi
ZAMM tincidunt cursus eu amet nunc
ZAMM c ac nunc, et pid pellentesque amet,
我正在使用:

$arrayst    = explode(" ", $string);

foreach($arrayst as $stringit) { 

    if(preg_match("/ZAMM.*/", $stringit, $matches)) {
       echo $stringit;
       echo "<br />";
    }

}

// Return:
ZAMM
arcu ZAMM
nunc ZAMM

为此,您需要在多行模式下使用正则表达式,因此可以使用
m
,查看整行数据

首先,我们查找一行的开头以及您希望在该行开头显示的数据:

^ZAMM
…然后我们查找任何不是新行的数据:

.+
我们可以在这里使用
,因为它不匹配新行,除非您还指定
s
修饰符,我们不会这样做。接下来,我们断言一行的结尾:

$
把这些放在一起,你会得到:

/^ZAMM.+$/m
在PHP中使用它:

$string ='ZAMM Et a est hac pid pid sit amet, lacus nisi
ZPPP scelerisque sagittis montes, porttitor ut arcu
ZAMM tincidunt cursus eu amet nunc
ZAMM c ac nunc, et pid pellentesque amet, 
ZSSS m urna scelerisque in vut';

preg_match_all('/^ZAMM.+$/m', $string, $matches);

print_r($matches[0]);

我更改了这个->
$arrayst=explode(“,$string”)
到这个->
$arrayst=explode(“\n”,$string)
因为字符串中也有
\n
(换行符),这只是我的观点,但您应该在每一行
\n
(换行符)

后面加上“
(换行符)

问题不在于正则表达式,而在于
分解(“,$string)
。执行此操作时,将字符串拆分为一个单词数组。你不会想要的!您希望正则表达式对整个字符串进行操作,而不是对每个单词进行操作

实际上,您想要的是正则表达式对字符串中的每一行进行操作

$string ='ZAMM Et a est hac pid pid sit amet, lacus nisi
ZPPP scelerisque sagittis montes, porttitor ut arcu
ZAMM tincidunt cursus eu amet nunc
ZAMM c ac nunc, et pid pellentesque amet, 
ZSSS m urna scelerisque in vut';

if(preg_match_all("/ZAMM.*/", $string, $matches)) {
    foreach($matches[0] as $match){
        echo $match;
        echo "<br />";
    }
}
$string='ZAMM Et a est hac pid sit amet,lacus nisi
ZPPP蒙特斯射手座十字勋章
扎姆·廷西德·库苏斯欧盟阿梅特·努克
扎姆·c·ac·努克和佩伦茨克·阿梅特,
ZSSS m urna scelerisque in vut';
if(preg_match_all(“/ZAMM.*/”,$string,$matches)){
foreach($matches[0]为$match){
回声$匹配;
回声“
”; } }

DEMO:

可以使用多行模式和至少一个主题断言的开始,这也将匹配行中的“代码> ZAMM ”;但总的来说+1@DaveRandom当前位置我读了你的答案,意识到这是一个更好的解决方案。我尝试使用
^$
但它不起作用,忘记了
m
标志:-D@AmmWeb:没问题,这就是我来这里的原因!:-D@AmmWeb:你是说没有新词?这将是一个挑战。是的,没有断线。如果我能公布结果的话,我也在这里尝试。非常感谢你的帮助非常感谢你的帮助
$string ='ZAMM Et a est hac pid pid sit amet, lacus nisi
ZPPP scelerisque sagittis montes, porttitor ut arcu
ZAMM tincidunt cursus eu amet nunc
ZAMM c ac nunc, et pid pellentesque amet, 
ZSSS m urna scelerisque in vut';

if(preg_match_all("/ZAMM.*/", $string, $matches)) {
    foreach($matches[0] as $match){
        echo $match;
        echo "<br />";
    }
}