PHP在找到HTML元素时分割内容

PHP在找到HTML元素时分割内容,php,string,Php,String,我有一个PHP变量,它包含一些HTML,我希望能够将变量拆分为两部分,我希望在找到第二个粗体或时发生拆分,基本上如果我有这样的内容 我的内容 这是我的内容一些更粗体的内容,这些内容将分散到另一个变量中 这有可能吗?类似的方法基本上是可行的: preg_split('/(<strong>|<b>)/', $html1, 3, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); preg_split('/()/”,$html1,

我有一个PHP变量,它包含一些HTML,我希望能够将变量拆分为两部分,我希望在找到第二个粗体
时发生拆分,基本上如果我有这样的内容

我的内容
这是我的内容一些更粗体的内容,这些内容将分散到另一个变量中


这有可能吗?

类似的方法基本上是可行的:

preg_split('/(<strong>|<b>)/', $html1, 3, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
preg_split('/()/”,$html1,3,preg_split_DELIM_CAPTURE | preg_split_NO_EMPTY);
考虑到您的测试字符串:

$html1 = '<strong>My content</strong>This is my content.<b>Some more bold</b>content';
$html1='我的内容这是我的内容。更多粗体内容';
你最终会得到

Array (
    [0] => <strong>
    [1] => My content</strong>This is my content.
    [2] => <b>
    [3] => Some more bold</b>content
)
数组(
[0]=>
[1] =>我的内容这是我的内容。
[2] => 
[3] =>更多粗体内容
)
现在,如果示例字符串不是以strong/b开头:

$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
)
$html2='像第一个一样,但是我的内容这是我的内容。一些更粗体的内容,有一些初始的无标记内容';
排列(
[0]=>像第一个,但是
[1] =>
[2] =>我的内容这是我的内容。
[3] => 
[4] =>一些更粗体的内容,有一些初始的无标记内容
)

还有一个简单的测试,看看元素#0是标记还是文本,以确定“第二个标记及其后续”文本的起始位置(元素#3或元素#4)

正则表达式中的“正向查找”是可能的。例如,
(?如果确实需要拆分字符串,正则表达式方法可能会起作用

如果您只想知道第二个节点有
strong
b
标记,那么使用
DOM
就容易多了。不仅代码非常明显,所有解析位都会为您处理好

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

是否可以将拆分放在它们自己的
div