您需要使用正则表达式吗?不必要。正则表达式是最可读的解决方案吗?可能不会 - 至少除非你在流利的正则表达式。扫描大量数据时,regex更有效吗?绝对的,正则表达式在第一次出现时被编译和缓存。正则表达式赢得“最少线代码”奖杯吗?
$string = <<<EOS
<html>
<body>
blahblah<br>
<img src='http://www.mysite.com/folder/subfolder/images/myimage.png'>blah<br>
blah<img src='http://www.mysite.com/folder/subfolder/images/another.png' />blah<br>
</body>
</html>
EOS;
preg_match_all("%<img .*?src=['\"](.*?)['\"]%s", $string, $matches);
$images = array_map(function ($element) { return preg_replace("%^.*/(.*)$%", 'images/$1', $element); }, $matches[1]);
print_r($images);
两行代码,很难在PHP中消退。它导致以下$images
数组:
Array
(
[0] => images/myimage.png
[1] => images/another.png
)
请注意,这不会与PHP之前的版本5.3工作,除非你有一个适当替换匿名函数。
[正则表达式来更改所有img src属性的格式]的可能重复(http://stackoverflow.com/questions/3131691/regex-to-change-format-of-all-img-src-attributes) – Gordon 2011-03-29 15:34:52