PHP在<img>标签上拆分或爆炸字符串

Mar*_*ing 6 php regex split explode html-parsing

我想将标签上的字符串拆分成不同的部分.

$string = 'Text <img src="hello.png" /> other text.';
Run Code Online (Sandbox Code Playgroud)

下一个功能还没有以正确的方式工作.

$array = preg_split('/<img .*>/i', $string);
Run Code Online (Sandbox Code Playgroud)

输出应该是

array(
    0 => 'Text ',
    1 => '<img src="hello.png" />',
    3 => ' other text.'
)
Run Code Online (Sandbox Code Playgroud)

我应该用什么样的模式来完成它?

编辑 如果有多个标签怎么办?

$string = 'Text <img src="hello.png" > hello <img src="bye.png" /> other text.';
$array = preg_split('/(<img .*>)/i', $string, -1, PREG_SPLIT_DELIM_CAPTURE);
Run Code Online (Sandbox Code Playgroud)

输出应该是:

array (
  0 => 'Text ',
  1 => '<img src="hello.png" />',
  3 => 'hello ',
  4 => '<img src="bye.png" />',
  5 => ' other text.'
)
Run Code Online (Sandbox Code Playgroud)

Fed*_*kun 4

你走在正确的道路上。您必须以这种方式设置标志PREG_SPLIT_DELIM_CAPTURE :

$array = preg_split('/(<img .*>)/i', $string, -1, PREG_SPLIT_DELIM_CAPTURE);
Run Code Online (Sandbox Code Playgroud)

正确编辑多个标签后,正则表达式:

$string = 'Text <img src="hello.png" > hello <img src="bye.png" /> other text.';
$array = preg_split('/(<img[^>]+\>)/i', $string, -1, PREG_SPLIT_DELIM_CAPTURE);
Run Code Online (Sandbox Code Playgroud)

这将输出:

array(5) {
  [0]=>
  string(5) "Text "
  [1]=>
  string(22) "<img src="hello.png" >"
  [2]=>
  string(7) " hello "
  [3]=>
  string(21) "<img src="bye.png" />"
  [4]=>
  string(12) " other text."
}
Run Code Online (Sandbox Code Playgroud)