我正在研究一些代码,并且我已经做了足够的工作来完成某些任务。我想在文本主体中替换图片网址和网页链接。Php preg_match和preg_replace带有url和图像标签的文本
EG“这是我的文字与http://www.google.com和某些图像http://www.somewebimage.png”
替换为“这是我的文字与<a href="http://www.google.com">http://www.google.com</a>
和某些图像<img src="http://www.somewebimage.png">
”
我砍得我更换网址或者IMG的链接,但并不both..one是在写入的,因为为了
$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;
}
的如果我阻止了$ reg_exUrl代码块,我得到的图像链接,如果它运行的我得到的URL链接。
我想要做的是一个简单的饲料,其中的URL链接被和IMG的URL被嵌入.. –
第一件事,测试用图案'preg_match'在与'preg_replace'一起使用之前是没有用的。 –
您应该为这两种情况使用单一模式,然后使用'preg_replace_callback'选择替换模板。这样一切都是一次完成的,没有任何东西被覆盖。在回调函数中,您可以使用'parse_url'和'explode'来轻松提取文件扩展名。 –