2015-09-22 26 views
0

我從服務器獲取一些文本,它看起來像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> 

如何獲得我需要的結構?

+0

E_TOO_MUCH_TEXT_TEXT_TEXT –

+0

你爲什麼從服務器上獲取這種格式的文本?我不會使用正則表達式來處理這種事情! – ajmedway

回答

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; 
} 

這是一種方法,通常我用這一個在這種情況下。

相關問題