简体   繁体   中英

PHP regex replace content in img src attribute?

I'm new to PHP and have following issue. I have to sanitize images and need to replace all img src if it starts with http:// with /files/images/ .

Is that possible to do with regex?

I found a similar solution here but it does't fulfil everything I need.

A modification of the thread you linked to do what you are requesting:

$dom = new DOMDocument();
$dom->loadHTML($content);

foreach ($dom->getElementsByTagName('img') as $img) {
    $current_src = $img->getAttribute('src');
    $new_src = preg_replace('http://', '/files/images', $current_src);
    $img->setAttribute( 'src', $new_src );
}

$content = $dom->saveHTML();

I don't have a machine with PHP readily available to test this for you (not at home), so let me know if you have any issues with it and I would be happy to troubleshoot for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM