墨竹论坛墨竹论坛
首页/ 技术交流/ 文章

分享一个PHP在线文本编辑器

分享一个PHP在线文本编辑器,思路是我自己的,但是代码部分是由各种人工智能共同努力下的结果[捂脸]

<?php
/**
* PHP在线文本编辑器
* JS控制DOM渲染,折叠状态不会把…按钮挤出可视区
* +添加按钮仅展开时显示;更新默认模板
* PHP5.6+
*/

$toolbarFile = __DIR__ . DIRECTORY_SEPARATOR . "editor_toolbar.txt";

$defaultTemplates = [
"<$>",
"</$>",
"=",
"<?php $?>",
"//$",
"/*$*/",
"$$value = $;"
];

if (!file_exists($toolbarFile)) {
file_put_contents($toolbarFile, implode("\n", $defaultTemplates) . "\n");
}

$rawToolbarLines = file($toolbarFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$templateListPhp = $rawToolbarLines ? $rawToolbarLines : $defaultTemplates;

$file_content = "";
$file_path = "";
$message = "";
$is_error = false;

if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (isset($_POST["action"]) && $_POST["action"] === "add_toolbar_item") {
$newItem = trim($_POST["tpl"] ?? "");
if ($newItem !== "") {
file_put_contents($toolbarFile, $newItem . "\n", FILE_APPEND);
}
header("Content-Type:application/json;charset=utf-8");
echo json_encode(["ok" => true]);
exit;
}

if (isset($_POST["read_file"])) {
$file_path = trim($_POST["file_path"]);
if (file_exists($file_path) && is_readable($file_path)) {
$file_content = file_get_contents($file_path);
$message = "成功读取文件:" . $file_path;
} else {
$message = "错误:文件不存在或无法读取!";
$is_error = true;
}
}

if (isset($_POST["save_file"])) {
$file_path = trim($_POST["file_path"]);
$new_content = $_POST["file_content"];
if (is_writable($file_path)) {
if (file_put_contents($file_path, $new_content)) {
$message = "文件保存成功!";
$file_content = $new_content;
} else {
$message = "错误:文件写入失败!";
$is_error = true;
}
} else {
$message = "错误:文件没有写入权限!";
}
}
}

$jsTemplateJson = json_encode($templateListPhp, JSON_HEX_TAG | JSON_HEX_APOS);
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>PHP在线文本编辑器</title>
<style>
:root{
--card-bg:#ffffff;
}
*{
box-sizing:border-box;
}
body {
font-family: system-ui, -apple-system, Arial, sans-serif;
margin: 0;
padding: 0;
padding-bottom: 110px;
background:#fafafa;
}
.container {
padding: 16px;
width:100%;
animation: fadeIn .6s ease;
}
@keyframes fadeIn {
from { opacity: 0; transform: translateY(12px); }
to { opacity: 1; transform: translateY(0); }
}
.form-group { margin-bottom: 14px; }
label { display: block; margin-bottom: 6px; font-weight: 500; font-size:14px; }
input[type="text"] {
width: 100%;
padding:10px 12px;
border:1px solid #ddd;
border-radius:8px;
font-size:14px;
background:#fff;
}
textarea {
width: 100%;
height: 52vh;
padding:12px;
border:1px solid #ddd;
border-radius:8px;
font-size:14px;
resize:vertical;
background:#ffffff;
}
.btn {
padding: 10px 18px;
border: none;
border-radius:8px;
cursor: pointer;
margin-right:10px;
font-size:14px;
}
.btn-read { background-color:#38b055; color:#fff; }
.btn-save { background-color:#2185d0; color:#fff; }
.message { padding:10px 12px; margin-bottom:14px; border-radius:8px; font-size:14px; }
.success { background-color:#eaf9ec; color:#207530; }
.error { background-color:#fde8e8; color:#b72c2c; }
hr {margin:18px 0; border:none;border-top:1px solid #e2e2e2;}

.mobile-toolbar{
display:none;
position:fixed;
bottom:0;
left:0;
width:100%;
background:#ffffff;
border-top:1px solid #e5e5e5;
box-shadow: 0 -2px 8px rgba(0,0,0,0.04);
padding:10px 12px;
}
.toolbar-wrap{
display:flex;
flex-wrap:wrap;
gap:8px;
}
.sym-btn{
flex-shrink:0;
border:1px solid #d8d8d8;
background:#f7f7f7;
padding:7px 12px;
border-radius:6px;
font-size:13px;
white-space:nowrap;
cursor:pointer;
}
.sym-btn:active{
background:#e9e9e9;
}
.sym-btn.more-dot{
background:#eef2f7;
color:#2266bb;
font-weight:bold;
}
.sym-btn.add{
background:#e8f4ff;
color:#0066bb;
}
.sym-btn.func{
background:#fff2dd;
color:#c26000;
}
</style>
</head>
<body>
<div class="container">
<h1 style="font-size:20px;margin:4px 0 16px 0;">PHP在线文本编辑器</h1>
<?php if ($message): ?>
<div class="message <?php echo $is_error ? 'error' : 'success'; ?>">
<?php echo htmlspecialchars($message); ?>
</div>
<?php endif; ?>

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
<div class="form-group">
<label for="file_path">服务器文件路径:(相对路径 ./ 代表当前目录)</label>
<input type="text" id="file_path" name="file_path"
placeholder="例如 C:/xampp/htdocs/test.txt"
value="<?php echo htmlspecialchars($file_path); ?>">
</div>
<button type="submit" name="read_file" class="btn btn-read">读取文件</button>
</form>
<hr>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
<input type="hidden" name="file_path" value="<?php echo htmlspecialchars($file_path); ?>">
<div class="form-group">
<label>文件内容:</label>
<textarea id="edit-textarea" name="file_content"><?php echo htmlspecialchars($file_content); ?></textarea>
</div>
<button type="submit" name="save_file" class="btn btn-save">保存文件</button>
</form>
</div>

<div class="mobile-toolbar" id="mobileToolbar">
<div class="toolbar-wrap" id="btnContainer"></div>
</div>

<script>
const textarea = document.getElementById("edit-textarea");
const toolbarEl = document.getElementById("mobileToolbar");
const btnContainer = document.getElementById("btnContainer");

const TAB_SPACE = 4;
// 折叠状态最多展示多少个用户模板,需要修改直接改这个数字
const FOLD_SHOW_TPL_COUNT = 5;
let templateList = <?php echo $jsTemplateJson; ?>;
let isExpanded = false;

function isMobile(){
return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
}

// 生成按钮界面显示文本
function getButtonDisplayText(rawTpl){
let s = rawTpl;
s = s.replace(/\$\$/g,"\x01");
s = s.replace(/\$/g,"");
s = s.replace(/\x01/g,"$");
return s;
}

// 模板插入解析逻辑
function processTemplate(rawTpl){
let str = rawTpl.replace(/\$\$/g,"\x00");
const cursorPosIndex = str.indexOf("$");
str = str.replace(/\x00/g,"$");

let insertText;
let offsetShift = 0;
if(cursorPosIndex !== -1){
insertText = str.slice(0,cursorPosIndex) + str.slice(cursorPosIndex+1);
offsetShift = cursorPosIndex;
}else{
insertText = str;
offsetShift = insertText.length;
}
return {insertText,cursorRelative:offsetShift};
}

function insertTemplate(tpl){
const {insertText,cursorRelative} = processTemplate(tpl);
const start = textarea.selectionStart;
const end = textarea.selectionEnd;
const oldVal = textarea.value;
const newVal = oldVal.substring(0,start) + insertText + oldVal.substring(end);
textarea.value = newVal;
const newCursor = start + cursorRelative;
textarea.selectionStart = newCursor;
textarea.selectionEnd = newCursor;
textarea.focus();
}

//缩进
function indentSelection(){
const start = textarea.selectionStart;
const end = textarea.selectionEnd;
const full = textarea.value;
const lineBegin = full.lastIndexOf("\n", start-1) + 1;
const selected = full.slice(lineBegin, end);
const lines = selected.split("\n");
const newLines = lines.map(line=>" ".repeat(TAB_SPACE)+line);
const newText = full.slice(0,lineBegin)+newLines.join("\n")+full.slice(end);
textarea.value = newText;
const selStartNew = start + TAB_SPACE;
const selEndNew = lineBegin + newLines.join("\n").length;
textarea.selectionStart = selStartNew;
textarea.selectionEnd = selEndNew;
textarea.focus();
}
function unindentSelection(){
const start = textarea.selectionStart;
const end = textarea.selectionEnd;
const full = textarea.value;
const lineBegin = full.lastIndexOf("\n", start-1) + 1;
const selected = full.slice(lineBegin, end);
const lines = selected.split("\n");
const newLines = lines.map(line=>{
let cnt = 0;
while(cnt<TAB_SPACE && line[0]===" "){
line = line.slice(1);
cnt++;
}
return line;
});
const newText = full.slice(0,lineBegin)+newLines.join("\n")+full.slice(end);
textarea.value = newText;
const delta = lines[0].length-newLines[0].length;
textarea.selectionStart = Math.max(lineBegin, start-delta);
textarea.selectionEnd = lineBegin + newLines.join("\n").length;
textarea.focus();
}

//光标移动
function cursorLeft(){
let pos = textarea.selectionStart;
pos = Math.max(0, pos - 1);
textarea.selectionStart = pos;
textarea.selectionEnd = pos;
textarea.focus();
}
function cursorRight(){
let pos = textarea.selectionStart;
pos = Math.min(textarea.value.length, pos + 1);
textarea.selectionStart = pos;
textarea.selectionEnd = pos;
textarea.focus();
}
function cursorUp(){
const pos = textarea.selectionStart;
const text = textarea.value;
const lineBegin = text.lastIndexOf("\n", pos - 1) + 1;
const col = pos - lineBegin;
if(lineBegin === 0) return;
const prevLineBegin = text.lastIndexOf("\n", lineBegin - 2) + 1;
const prevLineEnd = lineBegin -1;
const prevLineLen = prevLineEnd - prevLineBegin;
const newPos = prevLineBegin + Math.min(col, prevLineLen);
textarea.selectionStart = newPos;
textarea.selectionEnd = newPos;
textarea.focus();
}
function cursorDown(){
const pos = textarea.selectionStart;
const text = textarea.value;
const lineBegin = text.lastIndexOf("\n", pos -1) +1;
const col = pos - lineBegin;
const lineEnd = text.indexOf("\n", pos);
if(lineEnd === -1) return;
const nextLineBegin = lineEnd + 1;
const nextLineEnd = text.indexOf("\n", nextLineBegin);
const nextLineLen = (nextLineEnd === -1 ? text.length : nextLineEnd) - nextLineBegin;
const newPos = nextLineBegin + Math.min(col, nextLineLen);
textarea.selectionStart = newPos;
textarea.selectionEnd = newPos;
textarea.focus();
}

async function addTemplateRemote(tplText){
const fd = new FormData();
fd.append("action","add_toolbar_item");
fd.append("tpl", tplText);
await fetch("", {method:"POST", body:fd});
}

function renderButtons(){
btnContainer.innerHTML = "";

//=====系统功能按钮,折叠/展开永远显示=====
const btnUp = document.createElement("button");
btnUp.className = "sym-btn func";
btnUp.textContent = "↑";
btnUp.onclick = e=>{e.preventDefault();cursorUp();};
btnContainer.appendChild(btnUp);

const btnDown = document.createElement("button");
btnDown.className = "sym-btn func";
btnDown.textContent = "↓";
btnDown.onclick = e=>{e.preventDefault();cursorDown();};
btnContainer.appendChild(btnDown);

const btnLeft = document.createElement("button");
btnLeft.className = "sym-btn func";
btnLeft.textContent = "←";
btnLeft.onclick = e=>{e.preventDefault();cursorLeft();};
btnContainer.appendChild(btnLeft);

const btnRight = document.createElement("button");
btnRight.className = "sym-btn func";
btnRight.textContent = "→";
btnRight.onclick = e=>{e.preventDefault();cursorRight();};
btnContainer.appendChild(btnRight);

const btnIndent = document.createElement("button");
btnIndent.className = "sym-btn func";
btnIndent.textContent = "→缩进";
btnIndent.onclick = e=>{e.preventDefault();indentSelection();};
btnContainer.appendChild(btnIndent);

const btnUnindent = document.createElement("button");
btnUnindent.className = "sym-btn func";
btnUnindent.textContent = "←退缩进";
btnUnindent.onclick = e=>{e.preventDefault();unindentSelection();};
btnContainer.appendChild(btnUnindent);

let showTplList;
let hasMore;
if(isExpanded){
showTplList = [...templateList];
hasMore = false;
}else{
showTplList = templateList.slice(0,FOLD_SHOW_TPL_COUNT);
hasMore = templateList.length > FOLD_SHOW_TPL_COUNT;
}

//渲染模板按钮
showTplList.forEach(rawTpl=>{
const btn = document.createElement("button");
btn.className = "sym-btn";
btn.textContent = getButtonDisplayText(rawTpl);
btn.title = "原始模板:"+rawTpl;
btn.onclick = (e)=>{
e.preventDefault();
insertTemplate(rawTpl);
};
btnContainer.appendChild(btn);
});

//更多/收起按钮
if(hasMore || isExpanded){
const moreBtn = document.createElement("button");
moreBtn.className = "sym-btn more-dot";
moreBtn.textContent = isExpanded ? "收起" : "…";
moreBtn.onclick = (e)=>{
e.preventDefault();
isExpanded = !isExpanded;
renderButtons();
};
btnContainer.appendChild(moreBtn);
}

// +添加按钮:只有展开状态才渲染
if(isExpanded){
const addBtn = document.createElement("button");
addBtn.className = "sym-btn add";
addBtn.textContent = "+添加";
addBtn.onclick = async (e)=>{
e.preventDefault();
const inputTpl = prompt("输入快捷模板( $=光标位置,$$输出$ )","");
if(!inputTpl || inputTpl.trim()==="") return;
const t = inputTpl.trim();
templateList.push(t);
renderButtons();
await addTemplateRemote(t);
};
btnContainer.appendChild(addBtn);
}
}

window.addEventListener("DOMContentLoaded",()=>{
if(isMobile()){
toolbarEl.style.display="block";
}
renderButtons();
});

window.addEventListener("resize",()=>{
if(isMobile()) renderButtons();
});
</script>
</body>
</html>

可以给点建议,或者锐评🐶

(这论坛怎么现在这么清静?来点人呗)

评论(8)

登录 后参与评论
不凡之路 2026-11-03 22:23:41
不对呀,你这个代码渲染怎么是不行的?@小清墨
小清墨 2026-11-06 20:01:26 回复
em有没有可能你代码里面有php他只支持html
不凡之路 2026-11-07 21:26:30 回复
那行,我测试一下普通HTML
不凡之路 2026-11-07 21:38:45 回复
不管什么语言都不行啊
不凡之路 2026-11-08 13:06:38 回复
可以可以,终于修好了
小清墨 2026-11-08 13:15:06 回复
怎么说
小清墨 2026-11-08 13:15:12 回复
怎么说
不凡之路 2026-11-13 13:44:26 回复
?