I want to add a url before all the image sources not having “http” as protocol..For instance
<?php
$string ='<img src="image.jpg" alt=212><img src="http://upload.wikimedia.org/wikipedia/commons/e/e5/Raster_to_Vector_Mechanical_Example.jpg" alt=45>';
$pattern = '/(<img src=)\"[^http]/i';
$content = preg_replace($pattern, 'new_content', $string);
var_dump( $content);
?>
The previous script returns
string(132) "new_contentmage.jpg" alt=212><img src="http://upload.wikimedia.org/wikipedia/commons/e/e5/Raster_to_Vector_Mechanical_Example.jpg" alt="45">"
It has been able to identify the image source not starting with “http” but it has matched the next char in the source name, the ‘i’ in image.jpg and overwritten it with “new_content” text..
How can I add the string without overwriting the first char of the source name.
Regards
You need to use a negative lookahead:
This is because
[^http]does not do what you think it does; it actually matches exactly once any character that is either noth, or nott, or notp. Since all characters satisfy this, the first characteriinimage.jpgmatches.See it in action.