如何使用新行或行尾将mysql数据库中的字符串拆分为2个部分?

时间:2017-05-10 23:07:37

标签: php arrays string explode

我有一个从可能有多个换行符的数据库字段设置的变量。我想要一些PHP代码,它将文本从该变量拆分为2个单独的变量(或具有2个值的数组),仅使用第一个换行符作为分隔符。

所以你理解我要做的事情,变量来自的数据库字段是一条帖子消息,我基本上想要使用第一行文本的第一位文本作为帖子标题和之后的所有内容作为发布消息。

一个例子如下:

  

$ myvariable =“你相信今天发生了什么吗?\ n这辆伟大的大巴士   几乎让我过来了。然后我跳开了。\ n然后别的   发生了,它更加疯狂。\ n最后,我决定回家   小睡,因为这一天太疯狂了。\ n我喜欢大象   裤子,适合我\ nSNUGG!“;

     

我的新变量将成为:

     

$ title_from_myvariable =“你相信今天发生了什么吗?”;

     

$ message_from_myvariable =“这辆伟大的大巴车几乎让我过来了。   然后我跳开了。\ n然后发生了其他事情,事实就是如此   更加疯狂。\ n最后,我决定回家休息,因为   那天太疯狂了。\ n我喜欢大象裤,合身   我\ nSNUGG!“;

我已经看过几种使用\ n作为分隔符并使用explode的方法,我也使用explode查看了PHP_EOL。

关于这一点有一些很好的主题,如下所示:

How to put string in array, split by new line?

Explode PHP string by new line

问题是我是否使用如下代码:

$new_array_with_new_variables = explode("\n", $myvariable);

$new_array_with_new_variables = explode("PHP_EOL", $myvariable);

我最终将每条新行拆分为变量......

那里有超级编码员的建议吗?我只是想不出来这个!

2 个答案:

答案 0 :(得分:0)

这是一种有效的方法。

<?php
$pieces = explode("\n", $myvariable);
$title_from_myvariable = $pieces[0];
$message_from_myvariable = implode("\n", array_slice($pieces, 1, count($pieces) - 1));

答案 1 :(得分:-1)

以下内容可以满足您的需求。

$new_array_with_new_variablesTMP = explode("\n", $myvariable);
$new_array_with_new_variables = array($new_array_with_new_variablesTMP[0]);
array_shift($new_array_with_new_variablesTMP);
array_push($new_array_with_new_variables, implode('\n', $new_array_with_new_variablesTMP));

print_r($new_array_with_new_variables);

结果:

Array
(
    [0] => Do you believe what happened today?
    [1] => This great big bus almost ran me over. Then I jumped out of the way.\nThen something else happened and it was more crazy.\nFinally I decide to go home and have a nap because the day was just going too crazy.\nI like elephant pants, the fit me\nSNUGG!
)

现场直播: http://sandbox.onlinephpfunctions.com/code/0ff2eeb5fb73593a2baa6b6abd88878281ac9acf