簡體   English   中英

PHP - 查找並轉換所有鏈接和圖像以在 HTML 中顯示它們

[英]PHP - find and convert all links and images to display them in HTML

我看過很多與此相關的主題,但找不到適用於鏈接和圖像的內容。

在我的 PHP 頁面上,我回顯 $content,其中包含來自我的數據庫的記錄。 在這個字符串中,可以有網址和圖片網址。 我需要的是一個自動查找這些 url 並以正確的 HTML 顯示它們的函數。 因此,普通鏈接應顯示為<a ...>....</a> ,圖像鏈接(以 jpeg、jpg、png、gif、...結尾)應顯示為<img ...>

這是我僅在 url 網站鏈接中找到的內容:

$content = preg_replace("~[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]~",
                        "<a href=\"\\0\">\\0</a>", 
                        $content);

echo $content; 

我想我應該為此使用一些正則表達式代碼,但我對此不是很熟悉。非常感謝!

編輯:

http://example.comhttps://example.com都應該顯示為<a href="url">url</a> 所有不是圖片的網址;

http://www.example.com/image.png應顯示為<img src="http://www.example.com/image.png">這適用於所有以 png 等圖像擴展名結尾的網址, jpeg、gif 等

轉換您的項目(圖像和鏈接)的一種方法是首先應用更具體的模式,然后在其他模式中對src='使用負回顧:

<?php
$content = "I am an image (http://example.com/image.png) and here's another one: https://www.google.com/image1.gif. I want to be transformed to a proper link: http://www.google.com";

$regex_images = '~https?://\S+?(?:png|gif|jpe?g)~';
$regex_links = '~
                (?<!src=\') # negative lookbehind (no src=\' allowed!)
                https?://   # http:// or https://
                \S+         # anything not a whitespace
                \b          # a word boundary
                ~x';        # verbose modifier for these explanations

$content = preg_replace($regex_images, "<img src='\\0'>", $content);
$content = preg_replace($regex_links, "<a href='\\0'>\\0</a>", $content);
echo $content;
# I am an image (<img src='http://example.com/image.png'>) and here's another one: <img src='https://www.google.com/image1.gif'>. I want to be transformed to a proper link: <a href='http://www.google.com'>http://www.google.com</a>
?>

ideone.com上查看演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM