Строка до 3-х массивов с PHP - PullRequest
0 голосов
/ 14 декабря 2011

Привет, ребята, у меня есть блок текста, который я хочу разделить на три части, но я заметил, что нет ничего общего с этими частями, которые я мог бы использовать как разделитель для функции explode ().

$description = '£5.97 for a Pillowheads Children’s Backpack worth £11.95 from Intelex Ltd - save 50% on your choice of five adorable designsNeed to know: Save 50% on an Intelex Ltd Pillowheads Children’s Backpack; Choose from five cute and cuddly designs; Postage and packaging is not included and costs £3.95; The perfect stocking filler this Christmas; What & why: Give your little ones an adorably cute, yet totally practical gift this Christmas with a cuddly creature that doubles as a backpack! For just £5.97 choose one of these gorgeous little Pillowheads Children’s Backpacks from Intelex Ltd. With a gorgeous selection of five fluffy animals to choose from, there's sure to be a pack to suit your little pride and joy! Designed with high-quality adjustable back straps and an inner lining for maximum support, these versatile bags will please even the most fussiest of toy lovers! choose one of the following designs: - Cosy Bee - Ladybird - Monkey - Pig - Puppy Each backpack is 43cm x 20xm in size and can be surface cleaned with a damp sponge. about Intelex Ltd Innovators of the muscle-relieving microwaveable herbal heat pack, Intelex Ltd have set the industry standard for quality and safety. Discover an inexpensive, fun and soothing way to relax in comfort at home with a range of products that combine practicality, comfort and style.By the way: Multiple vouchers may be purchased; This product is suitable for children aged three years ; and over; To order, please phone             0871 911 1770      , quoting your unique kgbdeals voucher code, stating which style you would like and provide your delivery details; Please allow 48 hours for your voucher code to be ; activated';

Есть ли способ, которым я могу разделить это, 3 блока нужно знать: что и почему и кстати?

РЕДАКТИРОВАТЬ:

$description = preg_split('/Need to know:| What & why:|By the way:/i', $product['text']['desc'], 3);

Ладно, кстати, есть бит в массиве, но биты «нужно знать» и «что и почему» находятся в одном массиве, может кто-нибудь помочь с этим? :)

Ответы [ 5 ]

3 голосов
/ 14 декабря 2011
preg_split('/Need to know:|What & why:|By the way:/i', ''£5.97 for a Pillowheads Children?s Backpack worth £11.95 from Intelex Ltd - save 50% on your choice of five adorable designsNeed to know: Save 50% on an Intelex Ltd Pillowheads Children?s Backpack; Choose from five cute and cuddly designs; Postage and packaging is not included and costs £3.95; The perfect stocking filler this Christmas; What & why: Give your little ones an adorably cute, yet totally practical gift this Christmas with a cuddly creature that doubles as a backpack! For just £5.97 choose one of these gorgeous little Pillowheads Children?s Backpacks from Intelex Ltd. With a gorgeous selection of five fluffy animals to choose from, there's sure to be a pack to suit your little pride and joy! Designed with high-quality adjustable back straps and an inner lining for maximum support, these versatile bags will please even the most fussiest of toy lovers! choose one of the following designs: - Cosy Bee - Ladybird - Monkey - Pig - Puppy Each backpack is 43cm x 20xm in size and can be surface cleaned with a damp sponge. about Intelex Ltd Innovators of the muscle-relieving microwaveable herbal heat pack, Intelex Ltd have set the industry standard for quality and safety. Discover an inexpensive, fun and soothing way to relax in comfort at home with a range of products that combine practicality, comfort and style.By the way: Multiple vouchers may be purchased; This product is suitable for children aged three years ; and over; To order, please phone 0871 911 1770 , quoting your unique kgbdeals voucher code, stating which style you would like and provide your delivery details; Please allow 48 hours for your voucher code to be ; activated'', null, 1);

Результат:

    Array
(
    [0] => '£5.97 for a Pillowheads Children?s Backpack worth £11.95 from Intelex Ltd - save 50% on your choice of five adorable designs
    [1] =>  Save 50% on an Intelex Ltd Pillowheads Children?s Backpack; Choose from five cute and cuddly designs; Postage and packaging is not included and costs £3.95; The perfect stocking filler this Christmas; 
    [2] =>  Give your little ones an adorably cute, yet totally practical gift this Christmas with a cuddly creature that doubles as a backpack! For just £5.97 choose one of these gorgeous little Pillowheads Children?s Backpacks from Intelex Ltd. With a gorgeous selection of five fluffy animals to choose from, there's sure to be a pack to suit your little pride and joy! Designed with high-quality adjustable back straps and an inner lining for maximum support, these versatile bags will please even the most fussiest of toy lovers! choose one of the following designs: - Cosy Bee - Ladybird - Monkey - Pig - Puppy Each backpack is 43cm x 20xm in size and can be surface cleaned with a damp sponge. about Intelex Ltd Innovators of the muscle-relieving microwaveable herbal heat pack, Intelex Ltd have set the industry standard for quality and safety. Discover an inexpensive, fun and soothing way to relax in comfort at home with a range of products that combine practicality, comfort and style.
    [3] =>  Multiple vouchers may be purchased; This product is suitable for children aged three years ; and over; To order, please phone 0871 911 1770 , quoting your unique kgbdeals voucher code, stating which style you would like and provide your delivery details; Please allow 48 hours for your voucher code to be ; activated'
)
1 голос
/ 14 декабря 2011

РЕДАКТИРОВАТЬ: Не обращайте внимания. Я неправильно прочитал пост. Оставляя контент, потому что он работает для произвольных строк.


Лично я бы разделил пробел. Возможно, есть и лучшие места, но не обошлось без особой специфики приложения.

Вот быстрый грязный подход (с использованием функции wordwrap ):

// Number of desired chunks
$chunks = 3;
$data = "LONG CHUNK OF TEXT HERE";

// Prep the data by removing newlines.
$data = str_replace("\n", '', $data);

// Use the built in wordwrap function to split to size
$data = wordwrap($data, ceil(strlen($data) / $chunks));

// Split on the newly inserted newlines
$parts = explode("\n", $data);

// $parts is now an array with $chunks number of parts, all about the same length.
0 голосов
/ 14 декабря 2011

Не так элегантно, как регулярные выражения, но:

$start2 = strpos($description, "What & why:");
$start3 = strpos($description, "By the way:"); 
$part1 = substr($description, 0, $start2);
$part2 = substr($description, $start2, $start3 - $start2);
$part3 = substr($description, $start3);

Редактировать: Сделайте это, чтобы исключить текст "Что и почему / Кстати":

$start2 = strpos($description, "What & why:") + strlen("What & why:");
$start3 = strpos($description, "By the way:") + strlen("By the way:");
$end1 = $start2 - strlen("What & why:");
$end2 = $start3 - strlen("By the way:") - $start2;

$part1 = substr($description, 0, $end1);
$part2 = substr($description, $start2, $end2);
$part3 = substr($description, $start3);
0 голосов
/ 14 декабря 2011

Просто разбить его по подстроке:

$description = "£5.97 for a Pillowheads Children’s Backpack worth £11.95 from Intelex Ltd - save 50% on your choice of five adorable designsNeed to know: Save 50% on an Intelex Ltd Pillowheads Children’s Backpack; Choose from five cute and cuddly designs; Postage and packaging is not included and costs £3.95; The perfect stocking filler this Christmas; What & why: Give your little ones an adorably cute, yet totally practical gift this Christmas with a cuddly creature that doubles as a backpack! For just £5.97 choose one of these gorgeous little Pillowheads Children’s Backpacks from Intelex Ltd. With a gorgeous selection of five fluffy animals to choose from, there's sure to be a pack to suit your little pride and joy! Designed with high-quality adjustable back straps and an inner lining for maximum support, these versatile bags will please even the most fussiest of toy lovers! choose one of the following designs: - Cosy Bee - Ladybird - Monkey - Pig - Puppy Each backpack is 43cm x 20xm in size and can be surface cleaned with a damp sponge. about Intelex Ltd Innovators of the muscle-relieving microwaveable herbal heat pack, Intelex Ltd have set the industry standard for quality and safety. Discover an inexpensive, fun and soothing way to relax in comfort at home with a range of products that combine practicality, comfort and style.By the way: Multiple vouchers may be purchased; This product is suitable for children aged three years ; and over; To order, please phone             0871 911 1770      , quoting your unique kgbdeals voucher code, stating which style you would like and provide your delivery details; Please allow 48 hours for your voucher code to be ; activated";

$d_length = strlen($description);
$part = (int) ($d_length / 3);

$p1 = substr($description, 0, $part);
$p2 = substr($description, $part, $part);
$p3 = substr($description, ($part*2));

echo $p1.PHP_EOL;
echo $p2.PHP_EOL;
echo $p3.PHP_EOL;

Демо: http://codepad.org/QIuklFW7

0 голосов
/ 14 декабря 2011

Если есть определенная длина, которую может содержать каждая часть, вы можете разделить их, используя функцию php strpos ().В противном случае вы можете проверить точку и капитал после каждой части?Надеюсь, это поможет.

...