替换<a> tag with its src attribute that have another attribute</a>

时间:2013-04-04 04:23:28

标签: php html regex html-parsing preg-replace

这样:

$text = '<img class="fruit" src="http://exmple.com/apple.png" id="apple"><BR>
<img class="fruit" src="http://exmple.com/Lemon.png" ><BR>
<img src="http://exmple.com/banana.png" class="fruit"><BR>';

$pattern = '/<img(.*) src="([^"].*)"(.*)\>/i'; //<--the problem
$replace = preg_replace($pattern, '$2', $text);
echo $replace;

告诉我:

http://exmple.com/apple.png" id="apple
http://exmple.com/lemon.png
http://exmple.com/banana.png" class="fruit

我只需要用src值替换它们;像这样:

http://exmple.com/apple.png
http://exmple.com/lemon.png
http://exmple.com/banana.png

codepad上获得了好几个小时,但仍然没有想要的$pattern;我之前得到similiar question但没有工作;我对ragex逻辑并不擅长,所以我需要帮助。

1 个答案:

答案 0 :(得分:3)

你的字符串中还有一个.

// This:
$pattern = '/<img(.*) src="([^"]*)"(.*)\>/i';

// Not this:
$pattern = '/<img(.*) src="([^"].*)"(.*)\>/i';

然而,要做一个奇怪的替换以删除你不想要的部分,我会考虑拉出你想要的部分并改为打印它们。

$matches = array();
preg_match_all('/<img.*?src="([^"]*)"/i', $text, $matches);
echo implode("\n", $matches[1]);