需要修剪绳子

时间:2018-12-13 05:15:28

标签: php

我有一个字符串:

[LVL 5] Steff_Kingston(ONLINE: 103)
[LVL 4] Oscar_Porsche(ONLINE: 733)
[LVL 3] Kenny_NewSide(ONLINE: 32)
[LVL 1] Juliette_Ortega(ONLINE: 290)Evgeniy_Kytyzov (phoenix tucson 
scottdale chandler brainburg saintrose mesa redrock events helpers ) 2018- 
12-12 23:51:54Esten_Middles (phoenix tucson scottdale chandler brainburg 
saintrose mesa redrock central events helpers ) 2018-12-12 
23:52:31Steff_Kingston 

但是我只需要:

[LVL 5] Steff_Kingston(ONLINE: 103)
[LVL 4] Oscar_Porsche(ONLINE: 733)
[LVL 3] Kenny_NewSide(ONLINE: 32)
[LVL 1] Juliette_Ortega(ONLINE: 290)

可以是:

[LVL 3] Kenny_NewSide(ONLINE: 32)
[LVL 1] Juliette_Ortega(ONLINE: 290)Evgeniy_Kytyzov (phoenix tucson 
scottdale chandler brainburg saintrose mesa redrock events helpers ) 2018- 
12-12 23:51:54Esten_Middles (phoenix tucson scottdale chandler brainburg 

我只需要

[LVL 3] Kenny_NewSide(ONLINE: 32)
[LVL 1] Juliette_Ortega(ONLINE: 290)

字符数可能会有所不同。我该怎么做? PHP

2 个答案:

答案 0 :(得分:0)

以下是将preg_split与环视一起使用的一种选择:

$input = "[LVL 5] Steff_Kingston(ONLINE: 103) "; // and the rest of your input
$parts = preg_split("/(?<=Juliette_Ortega\(ONLINE: 290\))(?=Evgeniy_Kytyzov)/", $input);
print_r($parts[0]);

[LVL 5] Steff_Kingston(ONLINE: 103)
[LVL 4] Oscar_Porsche(ONLINE: 733)
[LVL 3] Kenny_NewSide(ONLINE: 32)
[LVL 1] Juliette_Ortega(ONLINE: 290)

正则表达式逻辑说,要在之前Juliette_Ortega(ONLINE: 290)跟随Evgeniy_Kytyzov的任意点分割字符串。然后,我们仅保留拆分的第一部分,即您的预期输出。

答案 1 :(得分:0)

您可以通过在(ONLINE...)部分上拆分字符串,捕获拆分后的字符串,然后删除拆分数组中的最后一项来完成此操作:

$input = '[LVL 5] Steff_Kingston(ONLINE: 103)
[LVL 4] Oscar_Porsche(ONLINE: 733)
[LVL 3] Kenny_NewSide(ONLINE: 32)
[LVL 1] Juliette_Ortega(ONLINE: 290)Evgeniy_Kytyzov (phoenix tucson 
scottdale chandler brainburg saintrose mesa redrock events helpers ) 2018- 
12-12 23:51:54Esten_Middles (phoenix tucson scottdale chandler brainburg 
saintrose mesa redrock central events helpers ) 2018-12-12 
23:52:31Steff_Kingston ';
$parts = preg_split('/(\(ONLINE:\s+\d+\))/', $input, -1, PREG_SPLIT_DELIM_CAPTURE);
array_pop($parts);
echo join('', $parts);

输出:

[LVL 5] Steff_Kingston(ONLINE: 103) 
[LVL 4] Oscar_Porsche(ONLINE: 733) 
[LVL 3] Kenny_NewSide(ONLINE: 32) 
[LVL 1] Juliette_Ortega(ONLINE: 290)

Demo on 3v4l.org

更新

假设您实际要做的是删除(ONLINE: nnn)和下一个[LVL n]之间的任何内容,则可以只使用preg_replace

echo preg_replace('/(\(ONLINE:\s+\d+\)).*?(\[LVL|$)/s', "$1\n$2", $input);

Demo on 3v4l.org