I have tried:

$urlres = preg_match_all('#<img[^>]*?>#si', $site, $matches);
$checkhttp = preg_match('#src="http#si', $matches[0][$i], $checked);

if ($urlres = true) {for($i = 0, $size = sizeof($matches[0]); $i < $size; ++$i)
					{
					
					if ($checkhttp != true):
					$pattern = '#src="http:#';
					$replacement = 'src="';
					$replacement .= $link2;
					$string = $matches[0][$i];
					$result = preg_replace($pattern, $replacement, $string);
					echo $string;
					else:
					echo $matches[0][$i];				
					endif;
					
					
					

}
					}

can someone help me please

Dani AI

Generated

tried a regex-based approach and / correctly pointed out delimiter problems. Even with fixed delimiters, regex is brittle for HTML. A more robust way is to parse the document with PHP's DOMDocument, loop the <img> elements and test or normalize each src attribute (checks can use stripos for a fast "starts with http" test). This avoids fragile pattern matching and handles malformed tags more gracefully.

libxml_use_internal_errors(true);
$dom = new DOMDocument();
$dom->loadHTML($html);
foreach ($dom->getElementsByTagName('img') as $img) {
    $src = $img->getAttribute('src');
    if (stripos($src, 'http://') === 0 || stripos($src, 'https://') === 0) {
        // already absolute
    } elseif (strpos($src, '//') === 0) {
        $img->setAttribute('src', 'http:' . $src); // or preserve scheme
    } else {
        $img->setAttribute('src', rtrim($base, '/') . '/' . ltrim($src, '/'));
    }
}
echo $dom->saveHTML();

Notes: libxml_use_internal_errors(true) suppresses parse warnings for imperfect HTML. Protocol-relative URLs (starting //) and relative paths require explicit handling when converting to absolute URLs. For strict HTML5 parsing or very broken markup, consider an HTML5 parser or tidy before DOMDocument. Relevant PHP docs: DOMDocument class and libxml_use_internal_errors.

Recommended Answers

All 2 Replies

I'm not too sure as to what the second line should be but the first line should look as follows:

$urlres = preg_match_all('/<img[^>]+\>/i', $site, $matches);

I don't know where you got the "#s"s from, but you should replace those with a "/" like cwarn23 suggested. Doesn't PHP give you an error on your regexp lines?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.