【问题标题】:Format the content and display media格式化内容和显示媒体
【发布时间】:2018-08-16 12:44:04
【问题描述】:

我有一个可以输入内容的文本区域:

<textarea name="content" placeholder="Content"></textarea>

DB中内容列的类型为Text

所以我可以在那里添加文本,然后将该文本插入数据库:

$stmt = $conn->prepare('INSERT INTO content VALUES(?)');
$stmt->execute( [$content] );

然后我会在我网站的某个位置显示该内容:

$stmt = $conn->prepare('SELECT content FROM posts');
$stmt->execute();
$results = $stmt->fetchAll();

foreach( $results as $result ){
    echo '<div>'. $result .'</div>';
}

但是该内容随后显示为纯文本,所以如果我输入:

$content = "This content contains a URL http://example.com";

我得到:This content contains a URL http://example.com,所以链接没有显示为链接,而是纯文本。

如果我添加了图片:

$content = "http://example.com/images/img.jpg";

或视频:

$content = "http://example.com/images/video.mp4";

或来自 Youtube 的视频。

那我该怎么办?

我应该使用 PHP 还是 Javascript 来检查内容是否包含 URL/图像/视频,然后将相关的 html 元素添加到该 URL?

【问题讨论】:

  • 使用CKEditor 而不是textarea。它具有添加图像、链接和其他功能。
  • 您希望用户使用标记语言甚至类似 BBCOde 的样式,还是只想在保存“原始”表单的同时替换前端中的此类数据?
  • @NicoHaase,用户无法添加或编辑,由管理员管理
  • 好吧,无论那个 textarea 的用户是谁——我剩下的问题呢?
  • 为什么要使用 CKEditor 将 URL 包装在 HTML 标签中?!!天哪。

标签: javascript php html mysql sql


【解决方案1】:

我不建议使用像 CKEditor 这样的编辑器来将一些 URL 包装在标记中,正如其他人所提出的令人震惊的建议。这是解决简单任务的一种非常懒惰和昂贵(不一定是价格,而是文件大小和请求数量)的方法。

以下解决方案未经测试,正则表达式模式取自外部来源,因此很遗憾我无法保证它们的正确性。自己尝试一下,然后测试、测试、测试。

示例

// your string

$content = "This is the content https://example.com/images/image1.jpg";

// find all URLs in $content and add matches to $matches array

$regex = "#\bhttps?://[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/))#";
preg_match_all($regex, $content, $matches);

// loop through $matches array

foreach ($matches as $match) {

    // check each item in array and use regex to determine type

    if (preg_match('/\.(jpg|jpeg|png|gif)(?:[\?\#].*)?$/i', $match)) {
        $markup = '<img src="'.$match.'">';
    } else {
        $markup = '<a href="'.$match.'">'.$match.'</a>';
    }

    // now replace the $match'ed URL in $content with the right $markup

    str_replace($match, $markup, $content);

}

文档

preg_match_all:http://php.net/manual/en/function.preg-match-all.php

preg_match:http://php.net/manual/en/function.preg-match.php

str_replace:http://php.net/manual/en/function.str-replace.php

【讨论】:

    猜你喜欢
    • 2020-04-29
    • 1970-01-01
    • 2018-05-21
    • 2012-10-31
    • 1970-01-01
    • 2018-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多