我如何在第n个字段之后拆分字符串并从PHP中的其余部分创建一个数组?(How could I split a string after the n

编程入门 行业动态 更新时间:2024-10-19 21:20:20
我如何在第n个字段之后拆分字符串并从PHP中的其余部分创建一个数组?(How could I split a string after the n-th field and create an array from the remaining parts in PHP?)

我有以下字符串:

*/3 * * * * echo yes

我想要做的是创建一个包含2个元素的数组,其中元素在第5个字段之后彼此分开:

$result = [ "*/3 * * * *", "echo yes" ];

在Linux bash shell中我会使用:

echo "*/3 * * * * logger yes" | cut -d' ' -f1-5 echo "*/3 * * * * logger yes" | cut -d' ' -f6-

你可以看到它是一个cron-entry。 因此,编写RegEx会非常不方便,因为字段可能会发生变化。 好吧,我可以编写一个RegEx,它用空白分隔符将元素彼此分开,但我想知道PHP中是否有任何类似于GNU cut或awk函数,我可以使用它来分割这两个部分在第5场之后。

我怎么能用PHP实现相同的结果?

I have the following string:

*/3 * * * * echo yes

What I want to do is to create an array with 2 elements from that, where the elements are separated after the 5th field from each other:

$result = [ "*/3 * * * *", "echo yes" ];

In Linux bash shell I would have just used:

echo "*/3 * * * * logger yes" | cut -d' ' -f1-5 echo "*/3 * * * * logger yes" | cut -d' ' -f6-

As you can see it's an cron-entry. So writing a RegEx would be rather inconvenient as the fields can change. Ok, I could write a RegEx which splits the elements from each other with a whitespace delimiter, but I'm wondering is there any function in PHP which is similar too GNU cut or awk, which I could use for that which splits the two parts after the 5th field.

How could I achieve the same result with PHP?

最满意答案

尝试这个 :

$result = [ implode('', array_slice(explode(' ', $string), 0, 5), implode('', array_slice(explode(' ', $string), 5) ];

Try this :

$result = [ implode('', array_slice(explode(' ', $string), 0, 5), implode('', array_slice(explode(' ', $string), 5) ];

更多推荐

本文发布于:2023-08-04 22:40:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1423349.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   字段   字符串   创建一个   并从

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!