使用匹配组在PHP

时间:2016-12-21 10:52:13

标签: php regex

有以下文字:

$text = 'sometext bla bla <img src="images/aaa.png" border="0"> other text blabla'

以下正则表达式匹配所有标记,匹配的组#1采用网址本身(images/aaa.png

`\<img.+src\=(?:\"|\')(.+?)(?:\"|\')(?:.+?)\>`

演示:https://regex101.com/r/BWeKMX/1

如何替换匹配的网址(images/aaa.png)并将其替换为以下内容?

$desiredSolution = 'sometext bla bla #_BLOCK_#IMG:images/aaa.png#_BLOCK_# other text blabla'

preg_replace将是第一个想法,但我不知道如何将匹配的组1放在那里。

preg_replace('/\<img.+src\=(?:\"|\')(.+?)(?:\"|\')(?:.+?)\>/', "#_BLOCK_#IMG:" . I_NEED_TO_PUT_HERE_THE_MATCHED_GROUP_1 . "#_BLOCK_#, $text);

有任何帮助吗?提前谢谢!

编辑: $text可以包含多个图片。

1 个答案:

答案 0 :(得分:2)

preg_replace()函数的文档可以回答您的问题: http://php.net/manual/en/function.preg-replace.php

看看这个简化的例子:

<?php
var_dump(
  preg_replace(
    '|\<img.+src\=(?:")(.+?)(?:")(?:.+?)\>|',
    '#_BLOCK_#IMG:\\1#_BLOCK_#',
    'sometext bla bla <img src="images/aaa.png" border="0"> other text blabla'
  )
);

输出结果为:

string(71) "sometext bla bla #_BLOCK_#IMG:images/aaa.png#_BLOCK_# other text blabla"

这也适用于多个此类图像标记,该函数将替换所有次出现,如下所示:

<?php
var_dump(
  preg_replace(
    '|\<img.+src\=(?:")(.+?)(?:")(?:.+?)\>|',
    '#_BLOCK_#IMG:\\1#_BLOCK_#',
    <<<EOT
sometext bla
bla <img src="images/aaa.png" border="0"> other text
bla
bla <img src="images/bbb.png" border="0"> and going on with
further text
EOT
  )
);

显而易见的结果是:

string(143) "sometext bla
bla #_BLOCK_#IMG:images/aaa.png#_BLOCK_# other text
bla
bla #_BLOCK_#IMG:images/bbb.png#_BLOCK_# and going on with
further text"