您需要使用正則表達式嗎?不必要。正則表達式是最可讀的解決方案嗎?可能不會 - 至少除非你在流利的正則表達式。掃描大量數據時,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