Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
448 views
in Technique[技术] by (71.8m points)

php - Replacing image src in HTML tags?

I want to use regex to replace src html attributes. The HTML is not malformed and fortunately takes the same form in all the pages in the database - i.e.

<img src="http://x.y/z/1.png" />

I have code that works fine if there's only one image in the page. I want to know the best way to replace multiple images, as this one will replace all the image tags with the same string.

$result = $s->db_query("SELECT reviewFullText as f FROM reviews WHERE reviewsID = 155");
while($row = mysql_fetch_array($result))
{
    $body = stripslashes(html_entity_decode($row['f'], ENT_NOQUOTES, "UTF-8"));
    preg_match_all('/<img.*?(src=['|"]{0,1}.*?['|"]{0,1})[s|>]{1}/i', $body, $matches);
    for($i=0;$i<count($matches[0]);$i++)
    {
        $number = preg_replace("/[^0-9]/", '', $matches[0][$i]);
        echo preg_replace('/<img.*?(src=['|"]{0,1}.*?['|"]{0,1})[s|>]{1}/i', '<img src="http://x.y/a/' . $number . '.png"', $matches[0][$i]);
    }
}

So if the page contains two files, one called 1.png and one called 2.png the script should parse the numbers and replace them with a different url such as http://x.y/a/1.png and http://x.y/a/2.png.

I've heard preg_replace_callback is the best way to do this but I have no idea how to get this working... Help!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Don't use regular expressions for irregular languages like HTML. Use a parser instead. It will save you a lot of time and pain.

# Untested code:
$xml = new SimpleXml($xmlString);
foreach ($xml->xpath('//img') as $imgNode) {
    $imgNode->addAttribute('src', "http://x.y/a/" . $imgNode->getAttribute('src'));
}
echo $xml->asXML();

Note that you will need something like DOMDocument::loadHtml(), if your html is not xhtml (i.e. valid xml), but the idea remains the same.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...