2013-04-04 66 views
1

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

$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; 

give me:

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

All I need just replace them with their src value; like this:

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

Got hours on codepad,但仍然没有所需$pattern;我之前得到了similiar question,但没有工作;我在逻辑上并不擅长,所以我需要帮助。

+0

$模式= '' 让我知道这是否正常工作.. – 2013-04-04 04:27:09

+1

岂不DOM解析器像['DOMDocument'(http://php.net/manual/en/class。 domdocument.php)是一个更好的解决方案来刮'src'es? – 2013-04-04 04:28:40

+1

你能澄清你想要的吗?你想删除图片标签,并用src字符串替换它们? – loganfsmyth 2013-04-04 04:29:04

回答

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]); 
+0

完成;谢谢。 :D – egig 2013-04-04 04:39:26

+0

@Charlie很高兴帮助,我将在1秒内更新另一个建议。 – loganfsmyth 2013-04-04 04:40:13

+0

其实我需要重新格式化html文档而不丢失图像,我需要它全部是字符串;我会做'strip_tags($ doc,'');'并用src替换img;再次感谢你的建议。 – egig 2013-04-04 05:18:10