Bir HTML öğesi bulunduğunda PHP içerik bölünmüş

3 Cevap php

Ben bazı HTML iki parçaya bölmek değişkeni edebilmek isteyen tutan bir PHP değişkeni var ve ben istiyorum gerçekleşecek dökülen zaman ikinci bir <strong> or <b> bulundu kalın, ben aslında, içerik o Bu gibi görünüyor,

My content
This is my content. Some more bold content, that would spilt into another variable.

Bu olası tüm altındadır?

3 Cevap

Böyle bir şey temelde çalışmak:

preg_split('/(<strong>|<b>)/', $html1, 3, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);

Sizin testi dize Verilen:

$html1 = '<strong>My content</strong>This is my content.<b>Some more bold</b>content';

Eğer ile bitirmek istiyorum

Array (
    [0] => <strong>
    [1] => My content</strong>This is my content.
    [2] => <b>
    [3] => Some more bold</b>content
)

Şimdi, örnek dize güçlü / b ile başlamak olmadıysa:

$html2 = 'like the first, but <strong>My content</strong>This is my content.<b>Some more bold</b>content, has some initial none-tag content';

Array (
    [0] => like the first, but 
    [1] => <strong>
    [2] => My content</strong>This is my content.
    [3] => <b>
    [4] => Some more bold</b>content, has some initial none-tag content
)

element # 0 belirlemek için bir etiket veya metin ise ve basit bir test görmek için nerede "ikinci etiket ve sonrası" metin başlar (element # 3 veya eleman # 4)

Düzenli ifadelerde 'Pozitif Geriye İlerleme' ile mümkündür. Örneğin, (?<=a)b b (ve yalnızca b) cab ile eşleşen, fakat eşleşmezse bed ya da debt.

Senin durumunda, (?<=(\<strong|\<b)).*(\<strong|\<b) hile yapmak gerekir. O etiketleri <b> ya da isterseniz bir preg_split() call and make sure to set PREG_SPLIT_DELIM_CAPTURE <strong> dahil olmak üzere bu regex kullanın.

Eğer gerçekten gerçekten dize bölmek gerekiyorsa, düzenli ifade yaklaşım işe yarayabilir. HTML ayrıştırma hakkında birçok kırılganlıklar olsa vardır.

Sadece kullanarak, ya bir strong veya b etiketi olan ikinci düğümü bilmek istiyorsanız bir DOM çok daha kolaydır. Sadece çok açık kod, tüm ayrıştırma bitleri sizin için halledilir edilir.

<?php

$testHtml = '<p><strong>My content</strong><br>
This is my content. <strong>Some more bold</strong> content, that would spilt into another variable.</p>
<p><b>This should not be found</b></p>';

$htmlDocument = new DOMDocument;

if ($htmlDocument->loadHTML($testHtml) === false) {
  // crash and burn
  die();
}

$xPath = new DOMXPath($htmlDocument);
$boldNodes = $xPath->query('//strong | //b');

$secondNodeIndex = 1;

if ($boldNodes->item($secondNodeIndex) !== null) {
  $secondNode = $boldNodes->item($secondNodeIndex);
  var_dump($secondNode->nodeValue);
} else {
  // crash and burn
}