[英]PHP split string two parts by each other
I have string. 我有绳子。 for example 例如
$string = 1234567;
or 要么
$string = 1976324
How i can split each second. 我怎么可以每秒。 for example. 例如。
[0=>1357, 1=>246];
or 要么
[0=>1734, 1=>962];
You can do this way: 您可以这样做:
<?php
$string = 1234567;
$string = (string)$string;
$tmp[0] = "";
$tmp[1] = "";
for($i = 0; $i < strlen($string);$i++)
{
if($i % 2)
{
$tmp[1] .= $string[$i];
}
else
{
$tmp[0] .= $string[$i];
}
}
print_r($tmp);
?>
You could also use a combination of str_split, array_chunk and array_column. 您也可以结合使用str_split,array_chunk和array_column。
I am not recommending this, rather presenting another, alternate way of processing this that gave me some fun ;) 我不建议这样做,而是提出另一种替代处理方式,这给了我一些乐趣;)
Note :
array_column()
requires PHP 5.5+. 注意 :array_column()
需要PHP 5.5+。
Example Code : 示例代码:
php > $string = 1234567;
php > print_r(array_column(array_chunk(str_split($string, 1), 2), 0));
Array
(
[0] => 1
[1] => 3
[2] => 5
[3] => 7
)
php > print_r(array_column(array_chunk(str_split($string, 1), 2), 1));
Array
(
[0] => 2
[1] => 4
[2] => 6
)
Of course you may also concatenate that into strings: 当然,您也可以将其连接成字符串:
php > echo implode('', array_column(array_chunk(str_split($string, 1), 2), 1));
246
php > echo implode('', array_column(array_chunk(str_split($string, 1), 2), 0));
1357
You could use this 你可以用这个
<?php
$string = '1976324';
$halfPosition = ceil(strlen($string)/2);
var_dump([substr($string, 0, $halfPosition), substr($string, $halfPosition)]);
This function became OBSOLETE in PHP 5.3.0, and was DELETED in PHP 7.0.0. 该函数在PHP 5.3.0中成为过时,在PHP 7.0.0中被删除。 You can use eplode and Add a delimiter in your string 您可以在字符串中使用eplode并添加定界符
// Example 1
$pizza = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ", $pizza);
echo $pieces[0]; // piece1
echo $pieces[1]; // piece2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.