2017-01-25 106 views
2

我想劈成兩半的文本字符串,被銘記不:拆分HTML兩種用PHP

  • 突破的話
  • 突破HTML

爲了給你一個有點背景,我想寫一篇博客文章,並在它的中間插入廣告。

我周圍到處尋找一個答案,但唯一的選擇,我可以找到SO建議剝離所有HTML - 這是不是一個選項...

例子:

$string = "<div class='some-class'>Deasdadlights blasdasde holysadsdto <span>Bri<img src='#'>cable holystone blow the man down</span></div>"; 
    $length = strlen($string); 

    // At this point, something magical needs to split the string being mindful of word breaks and html 
    $pieces = array(
    substr($string, 0, ($length/2)), 
    substr($string, ($length/2), $length) 
); 

    echo $pieces[0] . " **Something** " . $pieces[1]; 

    // <div class="some-class">Deasdadlights blasdasde holysadsdto <spa **something**="" n="">Bri<img src="#">cable holystone blow the man down</spa></div> 
    // And there goes the <span> tag :'(

UPDATE

感謝@Naga的回答!對於需要它的人來說,這是一個稍微更加擴展的版本:

$string = ' 
    <section class="post_content"> 
    <p>Often half the battle is ensuring you get the time to respond to your reviews, the other half is remembering that the customer is always right and you should proceed with caution.</p> 
    <p>Some simple principles to keep in mind are to be <strong>positive</strong>, <strong>humble</strong>, <strong>helpful</strong>, and <strong>enthusiastic</strong>.</p> 
    <p>Some simple principles to keep in mind are to be <strong>positive</strong>, <strong>humble</strong>, <strong>helpful</strong>, and <strong>enthusiastic</strong>.</p> 
    </section> 
    '; 

    $dom = new DOMDocument(); 
    $dom->preserveWhiteSpace = false; 
    libxml_use_internal_errors(true); 
    $dom->loadHTML($string); // $string is the block page full/part html  
    $xpath = new DOMXPath($dom); 
    $obj = $xpath->query('//section[@class="post_content"]'); // assume this is the container div that where you want to inject 
    $nodes = $obj->item(0)->childNodes; 
    $half = $nodes->length/2; 

    $i = 0; 
    foreach($nodes as $node) { 
    if ($i === $half) { 
     echo "<div class='insert'></div>"; 
    } 
    echo $node->ownerDocument->saveHTML($node); 
    $i ++; 
    } 

回答

2

只是按字符串長度拆分會混淆輸出html。你需要找到你想要注入廣告的容器,然後計算子節點的html節點,然後在子節點之後通過廣告注入重新構建html子註釋。

防爆,

 $dom = new DOMDocument(); 
     $dom->preserveWhiteSpace = false; 
     libxml_use_internal_errors(true); 
     $dom->loadHTML($html); // $html is the block page full/part html  
     $xpath = new DOMXPath($dom); 

     $obj = $xpath->query('//div[@class="content"]'); // div[@class="content"] - assume this is the container div that where you want to inject 
     var_dump($obj); // you will get all the inner content 
     echo $htmlString = $dom->saveHTML($obj->item(0)); // you will have all the inner html 
     // after this count the all child nodes and inject your advert and reconstruct render the page. 

OR

以簡單的方式

,發現在HTML內容的中間恆定的文本標籤,並替換爲您注射+不變文本標籤的標籤。

防爆,

$cons = '<h3 class="heading">Some heading</h3>'; 
$inject = 'your advert html/text'; 
$string = str_replace = ($cons, $inject.$cons, $string);