PHP在<img/>标记上拆分或分解字符串

时间:2015-06-10 10:49:35

标签: php regex split html-parsing explode

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

$string = 'Text <img src="hello.png" /> other text.';

下一个功能还没有正确运行。

$array = preg_split('/<img .*>/i', $string);

输出应为

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

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

修改 如果有多个标签怎么办?

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

输出应为:

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

2 个答案:

答案 0 :(得分:2)

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

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

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

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

这将输出:

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."
}

答案 1 :(得分:1)

您还需要将非贪婪的字符()包含在here中,并强制它抓取第一个发生的实例。 '/(<img .*?\/>)/i'

所以你的示例代码将是:

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

var_dump($array);

打印的结果:

array(5) {
    [0] =>
    string(5) "Text "
    [1] =>
    string(23) "<img src="hello.png" />"
    [2] =>
    string(7) " hello "
    [3] =>
    string(21) "<img src="bye.png" />"
    [4] =>
    string(12) " other text."
}
相关问题