[英]Splitting String into array and display it by chunk
foreach($files as $file) {
$xname = basename($file['name'],'.jpg');
$tmp = preg_split("/[\s,-]+/",$xname,-1, PREG_SPLIT_NO_EMPTY);
echo "<pre>";
print_r($tmp);
echo "</pre>";
here is the example string "LR-147-TKW FLOWER RECT MIRROR FRAME" 这里是例如串“LR-147-千粒重FLOWER RECT镜框”
I have this line of code that splits my string to arrays. 我有这行代码将我的字符串拆分为数组。 What i want it do is to get the first 3 words which is "LR-147-TKW" and store it to a variable.
我想要做的是获取前三个单词“ LR-147-TKW”并将其存储到变量中。 how can i achieve this?
我怎样才能做到这一点? my array output is this
0] => BR [1] => 139 [2] => TKW [3] => DRESSER [4] => BUFFET [5] => MIRROR
我的数组输出是
0] => BR [1] => 139 [2] => TKW [3] => DRESSER [4] => BUFFET [5] => MIRROR
You can use explode() , here are some examples: 您可以使用explode() ,这是一些示例:
<?php
$str = 'LR-147-TKW FLOWER RECT MIRROR FRAME';
$parts = explode(' ',$str);
print_r($parts);
/*
Array
(
[0] => LR-147-TKW
[1] => FLOWER
[2] => RECT
[3] => MIRROR
[4] => FRAME
)
*/
$serial_parts = explode('-',$parts[0]);
print_r($serial_parts);
/*
Array
(
[0] => LR
[1] => 147
[2] => TKW
)
*/
$full = array_merge($serial_parts,$parts);
print_r($full);
/*
Array
(
[0] => LR
[1] => 147
[2] => TKW
[3] => LR-147-TKW
[4] => FLOWER
[5] => RECT
[6] => MIRROR
[7] => FRAME
)
*/
?>
this actually does the trick for you current input. 这实际上可以为您提供当前输入的技巧。 $tmp will contain LR-147-TKW after you execute this line of code:
执行以下代码行后,$ tmp将包含LR-147-TKW:
list($tmp) = explode(' ', $input);
How about using explode
: 如何使用
explode
:
$arr = explode(' ',$file);
echo arr[0];
using preg_split
is a bit of overkill for such a simple task... 对于这样一个简单的任务,使用
preg_split
有点preg_split
正...
If you want to avoid the array, it can be done using strpos and substr : 如果要避免使用数组,可以使用strpos和substr完成 :
$pos = strpos($file, ' ');
echo substr('abcdef', 0, $pos);
This is because preg_split("/[\\s,-]+/",...
splits your string where ever a comma, minus or space occurs. Change it to preg_split("/[\\s,]+/",...)
and it should give you the correct array. 这是因为
preg_split("/[\\s,-]+/",...
在可能出现逗号,减号或空格的地方分割您的字符串。将其更改为preg_split("/[\\s,]+/",...)
,它应该给您正确的数组。
Note that if you do that, your function won't split words like WELL-SPOKEN
. 请注意,如果这样做,函数将不会拆分
WELL-SPOKEN
类的词。 It will become one entry in your array. 它将成为数组中的一项。
Considering your string has same pattern. 考虑到您的字符串具有相同的模式。
$str = "LR-147-TKW FLOWER RECT MIRROR FRAME"; $ str =“ LR-147-TKW花式镜框”;
$str1 = explode(' ',$str); $ str1 = explode('',$ str);
echo $str1[0]; echo $ str1 [0];
添加到您的代码:
$tmp = array_slice($tmp,0,3);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.