EST. 2026 — Notes from real server work SYSADMIN · SECURITY · AI · DIRECTADMIN Issue 01
THE SYSADMIN ALMANAC
Home / Linux / Replace Words in 217 Rows Without Breaking Compounds or VARCHAR 255
Linux

Replace Words in 217 Rows Without Breaking Compounds or VARCHAR 255

by Ton-Or ·5 Dec 2026·11 min read
Replace Words in 217 Rows Without Breaking Compounds or VARCHAR 255

Thai has no spaces between words, so replacing words across a database leaves no word boundaries to work with. A single short word can be both the term that needs replacing and part of another word that must stay untouched. This work needs ordered rules and a fallback when the replacement is too long for the field.

1-minute summary

Symptom / problem
Renaming a job title across a whole site spread over 8 tables, where a plain REPLACE breaks compound words and the longer new word overflows VARCHAR 255
Who should read
People who must change wording site-wide in a database holding Thai text
Fix in short
Use regex rules ordered from specific to general, read the column limits from information_schema, run --dry first, and make the real run idempotent so a rerun changes 0 rows.
Jump to steps

While I was migrating a client's old website to a new one, the owner asked me to change a job title across the site. Staff were no longer to be called โค้ช, and the phrase โค้ชประจำสาขา had to be replaced everywhere. This term was embedded in more than two hundred rows of migrated content. It took me three passes in one day to get the wording the owner wanted, and the third pass was necessary because I had interpreted the instruction too narrowly.

All the content belonged to the website owner, who had requested both the migration and the wording changes. The business names, personal names, partner company names, table names, and replacement pairs used as examples are all fictional. The Thai language pitfalls and row counts are real.

Three passes in one day, and the one I interpreted too narrowly

  1. First pass: the owner said not to use โค้ช for staff. I changed the job title labels to the English word Trainer.
  2. Second pass: the owner replied that I should use the Thai term ผู้ฝึกสอน, and that two senior staff members should be called ที่ปรึกษา. I changed the labels, then replaced only the phrase โค้ชประจำสาขา in the content, affecting 45 rows.
  3. Third pass: I went back to ask what to do about the standalone word โค้ช still present in around 46 product listings and around 75 articles. The owner replied that this had already been answered: replace it. This pass changed 217 rows.

The mistake behind the third pass was not technical. The original instruction was to stop calling staff โค้ช. I interpreted it as referring only to the one phrase the owner had given as an example, and left the standalone word because I was afraid of changing too much. I ended up asking a question that had already been answered. The lesson is that if I am worried about changing too much, I should send a list of what I intend to leave unchanged and why, instead of narrowing the work first and asking afterward.

8 tableswith the term embedded in them
45 rowsin the phrase-only pass
217 rowsafter extending the rules to the standalone word
4 -> 9characters, original versus replacement
255VARCHAR limit for short list items
0 rowswhen run a second time

Why REPLACE() in SQL is not enough

The first approach that comes to mind is UPDATE ... SET col = REPLACE(col, 'โค้ช', 'ผู้ฝึกสอน'), one table at a time. It is quick and short, but the target word is part of several compound words that refer to things, not people, and must remain unchanged.

-- ดูก่อนว่า REPLACE ตรง ๆ จะไปโดนอะไรบ้าง (ยังไม่ UPDATE)
SELECT id,
       text_th AS before_text,
       REPLACE(text_th, 'โค้ช', 'ผู้ฝึกสอน') AS after_text
FROM item_includes
WHERE text_th LIKE '%โค้ช%'
LIMIT 20;

-- ผลที่ไม่ต้องการ:
--   ค่าเอไอโค้ช และโค้ชคอร์ส   ->  ค่าเอไอผู้ฝึกสอน และผู้ฝึกสอนคอร์ส

There were four groups of words in the data that needed to be excluded: เอไอโค้ช, แอปโค้ช, โค้ชชิ่ง, and โค้ชคอร์ส. In a language with spaces between words, word boundaries such as \b can solve this problem. But Thai runs words together throughout a sentence, so regex word boundaries do not help. The only workable approach is to check the characters immediately before and after the term.

REPLACE()

Replace every occurrence

It has no context, breaks compound words, and has no fallback when the result exceeds the column limit. In strict mode, the entire statement fails. Outside strict mode, text is silently truncated, and there is no report of which rows were touched.

Regex rules in a command

Replace according to context

lookbehind and lookahead protect compound words. Rules can be ordered, each rule has a short fallback, and each column's limit is known before writing. The command has --dry and reports row counts per table.

I have covered strict mode and silent truncation in two separate articles: VARCHAR pitfalls when importing Thai data and Legacy apps breaking after a server migration because of strict mode. This time, it is another side of the same issue: editing existing text in a way that makes it longer.

Rules in an array, ordered from specific to general

All the rules live in one array. Each rule has three fields: a pattern, a replacement, and a short replacement for when the field has insufficient room. preg_replace accepts an array of patterns and processes them in order. The output of each rule becomes the input to the next, so ordering is part of correctness.

// [pattern, คำแทน, คำแทนแบบสั้นเมื่อคอลัมน์ไม่พอ] ทำตามลำดับ เฉพาะไปทั่วไป
private const RULES = [
    // 1) วลีเฉพาะ ต้องมาก่อนคำเดี่ยว
    ['/โค้ชประจำสาขา/u', 'ผู้ฝึกสอนประจำสาขา', 'ผู้ฝึกสอน'],

    // 2) สองคนอาวุโสที่เจ้าของกำหนดชื่อตำแหน่งแยก (ชื่อสมมติ)
    ['/โค้ช\s*(สมชาย|มานี)/u', 'ที่ปรึกษา$1', 'ที่ปรึกษา$1'],

    // 3) คำเดี่ยว แต่ไม่ใช่ส่วนของคำประสมที่หมายถึงสิ่งของ
    ['/(?<!เอไอ)(?<!เอไอ )(?<![Aa][Ii] )(?<!แอป)โค้ช(?!ชิ่ง|คอร์ส)/u', 'ผู้ฝึกสอน', 'ทีมงาน'],

    // 4) ชื่อบริษัทคู่ค้าที่เขียนผิด ยืดหยุ่นเรื่องจุดและช่องว่าง
    ['/OldCo\s+Trading\s+Co\.?\s*,?\s*Ltd\.?/iu', 'NewCo Trading Co., Ltd.', 'NewCo Trading Co., Ltd.'],

    // 5) วลีที่เจ้าของให้เอาออกจากประวัติทีมงาน (แทนด้วยสตริงว่าง)
    ['/ได้รับรางวัลประจำปีเก่า\s*/u', '', ''],
];
RuleBeforeAfterSpecific firstโค้ชประจำสาขาดูแลทุกคลาสผู้ฝึกสอนประจำสาขาดูแลทุกคลาสTwo senior staffโค้ชสมชายนำเวิร์กช็อปที่ปรึกษาสมชายนำเวิร์กช็อปStandalone wordมีโค้ชรอรับที่หน้าห้องมีผู้ฝึกสอนรอรับที่หน้าห้องKeep compoundsค่าเอไอโค้ช และโค้ชคอร์สค่าเอไอโค้ช และโค้ชคอร์สResult over 255รวมโค้ช ... (long text)รวมทีมงาน ... (short term)
Rules run from specific to general: the first three rows are replaced, the fourth contains compounds protected by lookaround, and the last is a short field that needs a fallback.

Rules 1 and 3 show why the order matters. If the standalone-word rule runs first, the phrase โค้ชประจำสาขา still becomes ผู้ฝึกสอนประจำสาขา, but the short replacement will be wrong: this phrase should shorten to just ผู้ฝึกสอน, while the standalone word should shorten to ทีมงาน. Rule 2 must also run before rule 3 for the same reason. Otherwise, the two senior staff members will also be called instructors.

Rule 3 can be read in two parts.

  • Four lookbehinds protect cases where the target word comes at the end of a compound: เอไอโค้ช without a space, with a space, with AI written in English, and แอปโค้ช. PCRE lookbehinds need a known, fixed length. An unbounded quantifier such as \s* cannot go inside them, so the cases with and without a space need separate lookbehinds.
  • One lookahead protects cases where the target word comes at the start of a compound: โค้ชชิ่ง and โค้ชคอร์ส.

Every pattern needs the u flag so that PCRE treats the text as UTF-8 characters. Without it, PCRE works at the byte level. Matchers such as \s or a class in square brackets could match a byte in the middle of a Thai character.

I tested the rules with a short script before putting them into the actual command. There are two things to check: the result must be correct, and passing that result through the rules again must leave it unchanged.

<?php
// test_rules.php — php test_rules.php
const RULES = [ /* array เดียวกับข้างบน */ ];
$apply = fn (string $v, int $slot = 1) => preg_replace(array_column(RULES, 0), array_column(RULES, $slot), $v);

$cases = [
    'โค้ชประจำสาขาดูแลทุกคลาส'    => 'ผู้ฝึกสอนประจำสาขาดูแลทุกคลาส',
    'โค้ชสมชายนำเวิร์กช็อป'         => 'ที่ปรึกษาสมชายนำเวิร์กช็อป',
    'มีโค้ชรอรับที่หน้าห้อง'        => 'มีผู้ฝึกสอนรอรับที่หน้าห้อง',
    'ค่าเอไอโค้ช และโค้ชคอร์ส'   => 'ค่าเอไอโค้ช และโค้ชคอร์ส',     // ต้องไม่เปลี่ยน
    'AI โค้ช ภาษาไทย'         => 'AI โค้ช ภาษาไทย',           // ต้องไม่เปลี่ยน
    'OldCo  Trading Co.,Ltd.'     => 'NewCo Trading Co., Ltd.',
];
$bad = 0;
foreach ($cases as $in => $want) {
    $out = $apply($in);
    $again = $apply($out);                       // idempotent: รอบสองต้องเท่าเดิม
    $ok = $out === $want && $again === $out;
    $bad += $ok ? 0 : 1;
    echo ($ok ? '[OK]  ' : '[ERR] '), $in, ' -> ', $out, PHP_EOL;
}
exit($bad ? 1 : 0);

These rules are idempotent because the replacements do not contain the target word. Neither ผู้ฝึกสอน nor ที่ปรึกษา contains โค้ช, so there is nothing to match on the second pass. If a replacement ever contains the target word, this property disappears immediately, and the test above will flag it.

Personal names containing the target word

regex does not know what is a proper name. If a person's name, shop name, or place name begins with or contains the target word, the standalone-word rule will replace text inside that name. To prevent this, SELECT the rows containing the target word and read them manually, then run --dry every time a rule is added. Add any names found as lookahead exclusions or specific rules above the general rule.

Preventing overflow: query information_schema for the limits

The original word is 4 characters long, and the replacement is 9. Each replacement adds 5 characters to the text. TEXT columns are not a problem, but the table of items included in the price uses VARCHAR(255), and some rows already have text close to the limit. Two or three replacements are enough to exceed it.

I did not want to hardcode 255 because the development and production schemas might not match in every column. Instead, the command asks the database for each column's limit.

SELECT column_name, character_maximum_length
FROM information_schema.columns
WHERE table_schema = DATABASE()
  AND table_name = 'item_includes'
  AND character_maximum_length IS NOT NULL
  AND character_maximum_length < 65535;

character_maximum_length is measured in characters, not bytes, so PHP must use mb_strlen rather than strlen. For ผู้ฝึกสอน, strlen returns 27, while mb_strlen returns 9. Using the former would skip most rows that would actually fit. The condition below 65535 excludes the TEXT family of columns, leaving only VARCHAR columns with genuinely tight limits.

One column in one rowUse full termผู้ฝึกสอนOver limit?mb_strlen vs 255Use short termทีมงานStill over?YesNoNoUPDATE changed columnsYesseo_*: truncateAdd ellipsisOthers: skip rowwarn skipLimit from character_maximum_length, in characters, not bytes
When the result exceeds the column limit, try the short replacements first. If it still exceeds the limit, truncate seo_* fields; for other fields, skip that row and warn instead of letting the database truncate it.

When the result exceeds the limit, the fallback has three steps.

foreach ($cols as $c) {
    $v = (string) $row->{$c};
    if ($v === '') {
        continue;
    }
    $n = preg_replace(array_column(self::RULES, 0), array_column(self::RULES, 1), $v);
    $limit = $max[$c] ?? null;                         // เพดานจาก information_schema

    if ($n !== null && $limit && mb_strlen($n) > $limit) {
        // ขั้น 1: ลองใหม่จากข้อความเดิม ด้วยชุดคำสั้น
        $n = preg_replace(array_column(self::RULES, 0), array_column(self::RULES, 2), $v);
        if (mb_strlen($n) > $limit) {
            if (! str_starts_with($c, 'seo_')) {
                // ขั้น 3: ช่องเนื้อหา ไม่ตัดเอง ข้ามแล้วบอก
                $this->warn("skip $table#{$row->id}.$c (would exceed $limit chars)");
                continue;
            }
            // ขั้น 2: ช่อง SEO ตัดท้ายแล้วเติมจุดไข่ปลา
            $n = rtrim(mb_substr($n, 0, $limit - 1)).'…';
        }
    }
    if ($n !== null && $n !== $v) {
        $upd[$c] = $n;
    }
}

The important detail is that the short-replacement attempt must start from the original text $v, not from the full-replacement result, because that result no longer contains the target word for the rules to match.

Treating SEO fields separately is a decision about the damage truncation can cause. seo_title and seo_description remain usable after truncation because search engines truncate them anyway. But truncating an item included in the price can change its meaning and mislead customers. For fields like these, I have the command skip them and emit a warn so someone can rewrite the sentence manually.

Do not let the database do the truncation

Without an explicit length check, there are two outcomes. In strict mode, the UPDATE statement fails partway through the job. Outside strict mode, the database silently truncates the text, leaving a sentence cut off mid-word without an error. Both are worse than skipping the row and leaving a list for someone to fix.

Run --dry first, then update only changed columns

The scope covers 8 tables: product/service listings, daily schedules, items included in the price, services, articles, pages, reviews, and staff. It includes name columns, introductory text, content HTML, and SEO title and description fields.

private const FIELDS = [
    'items'         => ['name_th', 'excerpt', 'description_html', 'seo_title', 'seo_description'],
    'item_days'     => ['title_th', 'body_html'],
    'item_includes' => ['text_th'],
    'services'      => ['title_th', 'excerpt', 'body_html', 'seo_title', 'seo_description'],
    'posts'         => ['title_th', 'excerpt', 'body_html', 'seo_title', 'seo_description'],
    'pages'         => ['title_th', 'body_html'],
    'reviews'       => ['excerpt', 'body_html'],
    'staff'         => ['full_name_th', 'role_label_th', 'bio_th'],
];

public function handle(): int
{
    $dry = (bool) $this->option('dry');
    $count = [];
    foreach (self::FIELDS as $table => $cols) {
        if (! Schema::hasTable($table)) {
            continue;
        }
        // เหลือเฉพาะคอลัมน์ที่มีจริงบนเครื่องนี้ รันได้แม้ schema ต่างกันระหว่างเครื่อง
        $cols = array_values(array_intersect($cols, Schema::getColumnListing($table)));
        $max = collect(DB::select(
            'select column_name c, character_maximum_length m from information_schema.columns
             where table_schema = database() and table_name = ?', [$table]
        ))->filter(fn ($x) => $x->m && $x->m < 65535)->pluck('m', 'c');

        foreach (DB::table($table)->select(array_merge(['id'], $cols))->cursor() as $row) {
            $upd = [];
            // ... ลูปต่อคอลัมน์จากหัวข้อก่อนหน้า ...
            if ($upd) {
                $count[$table] = ($count[$table] ?? 0) + 1;
                if (! $dry) {
                    DB::table($table)->where('id', $row->id)->update($upd);
                }
            }
        }
    }
    $this->table(['table', 'rows changed'], collect($count)->map(fn ($n, $t) => [$t, $n])->values());
    $this->info(($dry ? '[dry] ' : '').array_sum($count).' rows');

    return self::SUCCESS;
}

I made three deliberate choices: read one row at a time with cursor() instead of loading the whole table into memory; write only columns whose values actually change, leaving rows with no changes untouched; and use the same summary table format at the end of both --dry and actual runs so they can be compared directly.

# 1) สำรองตารางที่จะแตะก่อน
mysqldump --single-transaction app_db items item_days item_includes services posts pages reviews staff \
  | gzip > ~/backup/pre-wording-$(date +%F-%H%M).sql.gz

# 2) ดูก่อน ไม่เขียน
php artisan app:content-wording --dry

# 3) รันจริง
php artisan app:content-wording

# 4) รันซ้ำทันที ต้องได้ 0 rows
php artisan app:content-wording --dry

Related work: a misspelled partner name and contact details for former staff

The same set of rules handled two other requests that arrived that day.

The first was a partner company's name misspelled on the history page. Before changing it, I checked the correct name against the public corporate registry rather than relying on memory. The pattern needed to tolerate periods and spaces because the old content had several versions of the same name: some with periods, some without, and some with double spaces. Rule 4 above shows that pattern using a fictional name.

The second issue was more serious: 3 former employees' names, phone numbers, chat IDs, and email addresses were not just on the staff page but embedded in 79 content items. Removing their staff pages alone was not enough.

Where found Number of items
Items included in the price 29
Articles 21
Product listings 14
Services 11
Unpublished drafts 3
Reviews 1
Total 79

These details were replaced with the company's central contact channels using a separate command that runs before the wording replacement command. I am not showing those rules because the rules themselves consist entirely of personal data. But the structure is identical: an array of rules, a --dry option, and 0 changes on a repeat run.

People's details are not just in the people table

A website with years of content will have staff names and phone numbers typed directly into articles, page footers, and price lists. Deleting a row from the staff table fixes only one page. Whenever someone leaves, search the entire database using that person's set of terms, including unpublished drafts.

Checking the results, and why this must run after every import

After the actual run, I checked the results in two ways. First, I spot-checked 60 product listing pages on production and found no remaining instances of the original term. Second, I ran the command again, and it changed 0 rows.

Position in the post-import sequenceimportThe source brings back old wording->Hide personal detailsNames, numbers, emails->Replace wordingThese rules->Fix old linksThe next command->Second pass --dry0 rows

The final difference between this command and manual editing is that it does not lock fields. The new site still pulls content from the old site periodically (weekly sync runs), and the source still uses the old wording. Every import therefore brings the old wording back. If I locked the content in these 217 rows against importer writes, content updates made by staff at the source would never come through again. The right approach is to let the import overwrite it, then reapply the rules every time. This command therefore has a fixed place in the post-import sequence. I covered which fields should be locked and which should be handled by rules in the article on reimports undoing manual edits. The command that runs after this one is the tool for fixing old website links embedded in content.

Replacing Thai words across a database requires thinking about three things at once: surrounding context because there are no word boundaries, length after replacement because the new wording is never the same length as the old wording, and repeat runs because the old data will return. The replacement pairs, compound-word exclusions, and short fallbacks are specific to this job. Other jobs need their own review of the actual data, always starting with --dry. If I have left anything unexplained or made a typo, I will come back and correct it later.

Want us to set this up?

Get help with server setup, configuration, migration, or troubleshooting. Save time for the work that matters.

Get a quote

Hit something like this? Stuck somewhere?

Come trade notes on the LinuxThai board

→ Continue on the board

Comments 0

No comments yet — be the first