php包装不同标签中的特定字符串

时间:2015-09-22 10:12:38

标签: php

我从服务器获得了一些看似

的文字
Title ||
text text text
text text text

Title ||
text text text
text text text
text text text
text text text

我需要添加不同的标签,使其看起来像

<div class="receipt__ingredients__table">
<div class="receipt__ingredients__table__row"><p class="receipt__ingredients__title">Title</p></div>
<div class="receipt__ingredients__table__row"><p>text text text</p></div>
<div class="receipt__ingredients__table__row"><p>text text text</p></div>
</div>

<div class="receipt__ingredients__table">
    <div class="receipt__ingredients__table__row"><p class="receipt__ingredients__title">Title</p></div>
    <div class="receipt__ingredients__table__row"><p>text text text</p></div>
    <div class="receipt__ingredients__table__row"><p>text text text</p></div>
    <div class="receipt__ingredients__table__row"><p>text text text</p></div>
</div>

这是我的代码

$receipt_ingredients = "Title ||
                    text text text
                    text text text

                    Title ||
                    text text text
                    text text text
                    text text text
                    text text text";

$receipt_ingredients = preg_replace('/^(.*?)\s*[|]{2}/m', '<p class="receipt__ingredients__title">$1</p>', $receipt_ingredients);


$receipt_ingredients = '<div class="receipt__ingredients__table__row">'.str_replace(array("\r","\n\n","\n"),array('',"\n","</div>\n<div class='receipt__ingredients__table__row'>"),trim($receipt_ingredients,"\n\r")).'</div>';

echo $receipt_ingredients;

但是我得到的结构看起来像是

 <div class="receipt__ingredients__table__row"><p class="receipt__ingredients__title">Title</p></div>
<div class="receipt__ingredients__table__row">text text text</div>
<div class="receipt__ingredients__table__row">text text text</div>
<div class="receipt__ingredients__table__row"><p class="receipt__ingredients__title">Title</p></div>
<div class="receipt__ingredients__table__row">text text text</div>
<div class="receipt__ingredients__table__row">text text text</div>
<div class="receipt__ingredients__table__row">text text text</div>
<div class="receipt__ingredients__table__row">text text text</div>  

如何获得我需要的结构?

1 个答案:

答案 0 :(得分:0)

尝试使用explode()。首先用空行爆炸,然后用||爆炸并最后通过换行符。

首先创建一个映射数组,如:

$exploded = array('blocks' => array(
0 => array(
    'title' => '',
    'text' => ''
),
1 => array(
    'title' => '',
    'text' => ''
)
));

// Explode and fill array
$exploded = array();
$blocks = explode('\r\n \r\n', $receipt_ingredients); // NOTE you have to check the newline char coming from the db and use that

foreach ( $blocks as $block ) {
    $parts = explode('||', $block);
    $block_array = array(
        'title' => $parts[0],
        'text' => count($parts) > 1 ? $parts[1] : ''
    );

    // You could also simply echo so you do not have to reiterate the array again

    $exploded[] = $block_array;
}

这是一种方法,通常我会在这种情况下使用这种方法。