PHP中的字符串操作:在第一个空格上拆分


String Manipulation in PHP: split on first space

在我的PHP 5.3应用程序中,我得到字符串

例如:ACTION data with lot of spaces

我需要将ACTION和"具有大量空间的数据"作为两个字符串。

我很少行动。

像这样使用explode()

print_R(explode(' ', 'ACTION data with lot of spaces', 2));

输出:

Array
(
    [0] => ACTION
    [1] => data with lot of spaces
)

请参阅此处的演示

如果我理解正确,你可以使用以下方法之一:

  1. 按空格拆分:list($action, $data) = explode(' ', $action_string, 2);

  2. 按正则表达式拆分:preg_match('/('w+)'s(.*)/', $action_string, $matches);$matches[1]将是动作,$matches[2]将是休息数据)

  3. 拆分和重新组合:$parts = explode(' ',$action_string); $action = array_shift($parts); $data = implode(' ', $parts);