简体   繁体   中英

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"

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. how can i achieve this? my array output is this 0] => BR [1] => 139 [2] => TKW [3] => DRESSER [4] => BUFFET [5] => MIRROR

You can use explode() , here are some examples:

<?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:

list($tmp) = explode(' ', $input);

How about using explode :

$arr = explode(' ',$file);
echo arr[0];

using preg_split is a bit of overkill for such a simple task...

If you want to avoid the array, it can be done using strpos and 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.

Note that if you do that, your function won't split words like WELL-SPOKEN . It will become one entry in your array.

Considering your string has same pattern.

$str = "LR-147-TKW FLOWER RECT MIRROR FRAME";

$str1 = explode(' ',$str);

echo $str1[0];

添加到您的代码:

$tmp = array_slice($tmp,0,3);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM