Как отформатировать текст для отправки по REST API WORDPRESS?

Ссылка скопирована
1 ответ

Необходимо подготовить текст для отправки по REST API Wordpress

ИСХОДНЫЙ ТЕКСТ

It's hard to believe, but I've never tested what actually happens if you do an rm -rf on the entire root partition. Once, early in my career, I made a mistake with a delete and ran a root delete. But it wasn't the rm command, it was something else. I don't remember the details anymore. Back then the servers were still ironclad and it really became a problem. The server had not been put into production yet, but I had already configured something on it. I immediately noticed the error and canceled the command. At first I thought it was nothing, but then I noticed that all symbolic links were missing, although the system was working in general and rebooted normally. I had to redo everything anyway.

And now I decided to see what would really happen after rm -rf / on a test virtualization. The command did not work in this form and asked me to add the --no-preserve-root key. I did so:
# rm -rf / --no-preserve-root

And everything was really deleted except the /dev partition and the loaded system modules in /sys/module/. And it was so mundane, without any special messages, fatal errors or anything else. You are sitting in a system where there is nothing but what was loaded into memory. The bash shell works, you can do something, but not much. There's no binary.

Only those utilities built into the shell work. For example, echo, pwd, type, cd, etc..:
# type cd
cd is a shell builtin
That is, you can move to /sys/module/. But you can't do anything there. You cannot connect to a new session or log in through the terminal. You cannot even do the reboot command. It's a binary, and it doesn't exist. Nevertheless

Преобразуем данный текст https://www.freeformatter.com/json-escape.html#bef...

На выходе:

It's hard to believe, but I've never tested what actually happens if you do an rm -rf on the entire root partition. Once, early in my career, I made a mistake with a delete and ran a root delete. But it wasn't the rm command, it was something else. I don't remember the details anymore. Back then the servers were still ironclad and it really became a problem. The server had not been put into production yet, but I had already configured something on it. I immediately noticed the error and canceled the command. At first I thought it was nothing, but then I noticed that all symbolic links were missing, although the system was working in general and rebooted normally. I had to redo everything anyway. rnrnAnd now I decided to see what would really happen after rm -rf / on a test virtualization. The command did not work in this form and asked me to add the --no-preserve-root key. I did so:rn# rm -rf / --no-preserve-rootrnrnAnd everything was really deleted except the /dev partition and the loaded system modules in /sys/module/. And it was so mundane, without any special messages, fatal errors or anything else. You are sitting in a system where there is nothing but what was loaded into memory. The bash shell works, you can do something, but not much. There's no binary. rnrnOnly those utilities built into the shell work. For example, echo, pwd, type, cd, etc..:rn# type cdrncd is a shell builtinrnThat is, you can move to /sys/module/. But you can't do anything there. You cannot connect to a new session or log in through the terminal. You cannot even do the reboot command. It's a binary, and it doesn't exist. Nevertheless

Собственно здесь все было отформатировано по правилам:

  • Backspace заменяется на b
  • Передача формы заменяется на f
  • Новая строка заменяется на n
  • Возврат каретки заменяется на r
  • Табуляция заменяется на t
  • Двойная кавычка заменяется на "
  • Обратная косая черта заменяется на \

Как это реализовать Через C# или JS? Чтобы не прибегать к онлайн сервисам

Дополнительно:

Вам подсказать, как у текса заменить определенные символы на другие?

Как отформатировать текст для отправки по REST API WORDPRESS?

String.Replace()

Нужно решить такую задачу?

Опишите проблему, и специалист поможет с настройкой, исправлением ошибки или доработкой сайта. Подберём понятный план работ без лишней переписки.

Заказать помощь
Лучший ответ
1
Анна SEO Ответ

Для отправки текста в WordPress REST API нужно передавать нормальный JSON, а HTML/переводы строк экранировать средствами JSON, а не руками. WordPress принимает контент записи в поле content. Если отправляете через curl, проще всего подготовить JSON-файл и отправить его как тело запроса.

Пример структуры:

{
  "title": "Заголовок записи",
  "status": "draft",
  "content": "<p>Первый абзац текста.</p><p>Второй абзац текста.</p>"
}

{ "title": "Заголовок записи", "status": "draft", "content": "<p>Первый абзац текста.</p><p>Второй абзац текста.</p>" }

Если исходный текст обычный plain text с переводами строк, преобразуйте абзацы в HTML на своей стороне. Два перевода строки — новый абзац, один перевод строки можно оставить как пробел или <br>, если это действительно нужно.

На JavaScript:

function textToHtml(text) {
    return text
        .split(/ns*n/)
        .map(function (part) {
            return '&lt;p&gt;' + part.trim().replace(/n/g, '&lt;br&gt;') + '&lt;/p&gt;';
        })
        .join('');
}

function textToHtml(text) { return text .split(/ns*n/) .map(function (part) { return '&lt;p&gt;' + part.trim().replace(/n/g, '&lt;br&gt;') + '&lt;/p&gt;'; }) .join(''); }

Главное — не собирать JSON строковой конкатенацией, особенно если в тексте есть кавычки, апострофы, обратные слэши и команды вроде rm -rf. Используйте JSON.stringify() или нормальный JSON-сериализатор в C#, PHP, Python.

Если контент содержит код, оборачивайте его в <pre><code> и отдельно экранируйте HTML-символы. Иначе WordPress может воспринять часть текста как HTML-разметку.

Другие ответы (0)

Пока нет других ответов. Будьте первым, кто поможет автору.

Ответить на вопрос

комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Вам также может быть интересно