Javascript 格式化内容和显示媒体
我有一个文本区,可以在其中输入内容:Javascript 格式化内容和显示媒体,javascript,php,html,mysql,sql,Javascript,Php,Html,Mysql,Sql,我有一个文本区,可以在其中输入内容: <textarea name="content" placeholder="Content"></textarea> 然后我会在我的网站上的某些地方显示这些内容: $stmt = $conn->prepare('SELECT content FROM posts'); $stmt->execute(); $results = $stmt->fetchAll(); foreach( $results as $res
<textarea name="content" placeholder="Content"></textarea>
然后我会在我的网站上的某些地方显示这些内容:
$stmt = $conn->prepare('SELECT content FROM posts');
$stmt->execute();
$results = $stmt->fetchAll();
foreach( $results as $result ){
echo '<div>'. $result .'</div>';
}
我得到:此内容包含一个URLhttp://example.com,因此该链接不会显示为链接,而是显示为纯文本
如果我添加了一个图像:
$content = "http://example.com/images/img.jpg";
或视频:
$content = "http://example.com/images/video.mp4";
或者Youtube上的视频
那我该怎么办
我是否应该使用PHP或Javascript检查内容是否包含URL/图像/视频,然后将相关html元素添加到该URL?我不建议像其他人所建议的那样,使用像CKEditor这样的编辑器将一些URL包装在标记中。这是一种非常懒惰和昂贵的解决简单任务的方法,不一定是价格,而是文件的大小和请求的数量 下面的解决方案未经测试,并且regex模式是从外部来源获取的,因此很遗憾,我不能保证它们的正确性。你自己试试,测试,测试,测试 范例 文件 预匹配所有: 预赛:
str_replace:使用CKEditor而不是textarea。它具有添加图像、链接和其他功能。您想让用户使用标记语言甚至BBCOde样式,还是只想在保存原始表单时替换前端的此类数据?@NicoHaase,用户无法添加或编辑,由管理员管理,不管该文本区域的用户是谁-我的问题的其余部分呢?为什么要使用CKEditor将URL包装在HTML标记中?!!天哪。
$content = "http://example.com/images/img.jpg";
$content = "http://example.com/images/video.mp4";
// 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);
}