【问题标题】:PHP split or explode string on <img> tagPHP 在 <img> 标签上拆分或分解字符串
【发布时间】:2015-06-10 10:49:35
【问题描述】:

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

$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.'
)

【问题讨论】:

    标签: php regex split html-parsing explode


    【解决方案1】:

    你走在正确的道路上。您必须以这种方式设置标志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."
    }
    

    【讨论】:

    • 这是过时的吗?当我尝试回显此代码时,我只看到:'array'
    • @twan,你是怎么用的?
    • 我已经修好了,用 echo 而不是 print_r($array) 哈哈。
    【解决方案2】:

    您还需要将here 中描述的非贪婪字符 (?) 包含到您的模式中,以强制它抓取第一个出现的实例。 '/(&lt;img .*?\/&gt;)/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."
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-03-12
      • 1970-01-01
      • 2023-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多