I am working on some code and I've done enough work to get something going. I want to replace a image url(s) and web links within that body of text.
E.G "This is my text with http://www.google.com and some image http://www.somewebimage.png"
Replace to "This is my text with <a href="http://www.google.com">http://www.google.com</a> and some image <img src="http://www.somewebimage.png">"
My hack gets me to replace the url(s) or the img links but not both..one is over written because of the order
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
$reg_exImg = '/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?(jpg|png|gif|jpeg)/';
$post = "This is my text with http://www.google.com and some image http://www.somewebimage.png";
if(preg_match($reg_exImg, $post, $img)) {
$img_post = preg_replace($reg_exImg, "<img src=".$img[0]." width='300' style='float: right;'> ", $post);
} else {
$img_post = $post;
}
if(preg_match($reg_exUrl, $post, $url)) {
$img_post = preg_replace($reg_exUrl, "<a href=".$url[0]." target='_blank'>{$url[0]}</a> ", $post);
} else {
$img_post = $post;
}
If I block the $reg_exUrl code block I get the image link if it runs the I get the url link.
preg_matchbefore using it withpreg_replaceis useless. - Casimir et Hippolytepreg_replace_callback. This way all is done in a single pass and nothing is overwritten. In the callback function you can useparse_urlandexplodeto easily extract the file extension. - Casimir et Hippolyte