Skip to content

emka.web.id

menulis pengetahuan – merekam peradaban

Menu
  • Home
  • Tutorial
  • Search
Menu

PHP Cookbook: Expanding and Compressing Tabs

Posted on February 18, 2012

Problem
You want to change spaces to tabs (or tabs to spaces) in a string while keeping text aligned with tab stops. For example, you want to display formatted text to users in a standardized way.

Solution
Use str_replace( ) to switch spaces to tabs or tabs to spaces, as shown in Example
1-22.
Example 1-22. Switching tabs and spaces
[sourcecode language=”php”]<?php
$r = mysql_query("SELECT message FROM messages WHERE id = 1") or die();
$ob = mysql_fetch_object($r);
$tabbed = str_replace(‘ ‘,"\t",$ob->message);
$spaced = str_replace("\t",’ ‘,$ob->message);
print "With Tabs: <pre>$tabbed</pre>";
print "With Spaces: <pre>$spaced</pre>";
?>[/sourcecode]

Using str_replace( ) for conversion, however, doesn’t respect tab stops. If you want tab stops every eight characters, a line beginning with a five-letter word and a tab should have that tab replaced with three spaces, not one. Use the pc_tab_expand( ) function shown in Example 1-23 into turn tabs to spaces in a way that respects tab stops.

Example 1-23. pc_tab_expand( )
[sourcecode language=”php”]<?php
function pc_tab_expand($text) {
while (strstr($text,"\t")) {
$text = preg_replace_callback(‘/^([^\t\n]*)(\t+)/m’,’pc_tab_expand_helper’, $text);
}
return $text;
}
function pc_tab_expand_helper($matches) {
$tab_stop = 8;
return $matches[1] .
str_repeat(‘ ‘,strlen($matches[2]) *
$tab_stop – (strlen($matches[1]) % $tab_stop));
}
$spaced = pc_tab_expand($ob->message);
?>
[/sourcecode]

You can use the pc_tab_unexpand( ) function shown in Example 1-24 to turn spaces back to tabs.

Example 1-24. pc_tab_unexpand( )
[sourcecode language=”php”]
<?php
function pc_tab_unexpand($text) {
$tab_stop = 8;
$lines = explode("\n",$text);
foreach ($lines as $i => $line) {
// Expand any tabs to spaces
$line = pc_tab_expand($line);
$chunks = str_split($line, $tab_stop);
$chunkCount = count($chunks);
// Scan all but the last chunk
for ($j = 0; $j < $chunkCount – 1; $j++) {
$chunks[$j] = preg_replace(‘/ {2,}$/’,"\t",$chunks[$j]);
}
// If the last chunk is a tab-stop’s worth of spaces
// convert it to a tab; Otherwise, leave it alone
if ($chunks[$chunkCount-1] == str_repeat(‘ ‘, $tab_stop)) {
$chunks[$chunkCount-1] = "\t";
}
// Recombine the chunks
$lines[$i] = implode(”,$chunks);
}
// Recombine the lines
return implode("\n",$lines);
}
$tabbed = pc_tab_unexpand($ob->message);
?>
[/sourcecode]

Both functions take a string as an argument and return the string appropriately modified.

Discussion
Each function assumes tab stops are every eight spaces, but that can be modified by changing the setting of the $tab_stop variable.

The regular expression in pc_tab_expand( ) matches both a group of tabs and all the text in a line before that group of tabs. It needs to match the text before the tabs because the length of that text affects how many spaces the tabs should be replaced with so that
subsequent text is aligned with the next tab stop. The function doesn’t just replace each tab with eight spaces; it adjusts text after tabs to line up with tab stops.

Similarly, pc_tab_unexpand( ) doesn’t just look for eight consecutive spaces and then replace them with one tab character. It divides up each line into eight-character chunks and then substitutes ending whitespace in those chunks (at least two spaces) with tabs. This not only preserves text alignment with tab stops; it also saves space in the string.

See Also
Documentation on str_replace( ) at http://www.php.net/str-replace, on preg_replace_callback( ) at http://www.php.net/preg_replace_callback, and on str_split( ) at http://www.php.net/str_split. Recipe 22.10 has more information on
preg_replace_callback( ) .

Terbaru

  • Inilah Alur Pengerjaan EMIS GTK 2026 yang Benar dari Awal Sampai Akhir
  • Inilah 27 Sekolah Kedinasan untuk Lulusan SMK 2026, Bisa Kuliah Gratis dan Langsung Jadi CPNS!
  • Inilah Cara Kuliah S2 di Inggris dengan GREAT Scholarship 2026: Syarat Lengkap, Daftar Kampus, dan Tips Jitu Biar Lolos!
  • Belum Tahu? Inilah Alasan Non-Muslim Juga Bisa Ngurangin Pajak Pake Sumbangan Keagamaan Wajib!
  • Inilah Kenapa Zakat ke Pondok Pesantren Mungkin Nggak Bisa Jadi Pengurang Pajak, Yuk Cek Syaratnya!
  • Inilah Caranya Daftar SMA Unggul Garuda Baru 2026 yang Diperpanjang, Cek Syarat dan Link Resminya!
  • Cara Cek Pencairan KJP Plus Tahap 1 Januari 2026 Beserta Daftar Nominal Lengkapnya
  • Lengkap! Inilah Kronologi Meninggalnya Vidi Aldiano Berjuang Melawan Kanker
  • Inilah Cara Tarik Data PKH di EMIS 4.0 Agar Bantuan Siswa Tetap Cair!
  • Inilah Trik Jitu SEO Shopee untuk Pemula: Jualan Laris Manis Tanpa Perlu Bakar Duit Iklan!
  • Inilah Peluang Emas Jadi Karyawan BUMN Tanpa Ngantre: Program Ikatan Kerja ULBI 2026
  • Inikah Daftar CPNS Kemenkeu 2026? Cek 48 Jurusan yang Paling Dibutuhkan!
  • Inilah 4 Beasiswa Khusus Warga ASEAN dengan Peluang Lolos Lebih Tinggi, Kalian Wajib Tahu!
  • Inilah Alasan Ribuan Dosen ASN Melayangkan Surat Keberatan Soal Tukin 2020-2024 yang Belum Cair
  • Cara Dapat Diamond Free Fire Gratis 2026, Pemain FF Harus Tahu!
  • Inilah Cara Mengisi Presensi EMIS GTK IMP 2026 Terbaru Biar Tunjangan Lancar
  • Inilah Trik Hashtag Viral Supaya Video Shorts Kalian Nggak Sepi Penonton Lagi
  • Inilah Jawabannya, Apakah Zakat Fitrah Kalian Bisa Mengurangi Pajak Penghasilan?
  • Inilah Caranya Supaya Komisi TikTok dan Shopee Affiliate Tetap Stabil Pasca Ramadhan!
  • Inilah 10 Kesalahan Fatal Saat Beli Properti yang Bisa Bikin Kalian Bangkrut!
  • Belum Tahu Cara Masuk Simpatika Terbaru? Ini Cara Login PTK EMIS GTK IMP 2026 Supaya Cek TPG Jadi Lebih Gampang!
  • Inilah Cara Bikin Konten Animasi AI Cuma Modal HP Supaya Bisa Gajian Rutin dari YouTube
  • Inilah Alasan Kenapa Zakat ke Ormas yang Belum Diakui Negara Nggak Bisa Dipakai Buat Ngurangin Pajak!
  • Inilah Cara Belanja di Indomaret Pakai Shopee PayLater yang Praktis dan Bikin Hemat!
  • Inilah 10 Jurusan Terfavorit di Universitas Negeri Semarang Buat SNBT 2026, Saingannya Ketat Banget!
  • Belum Tahu? Inilah Cara Mudah Membuat Akun dan Login EMIS GTK IMP 2026 yang Benar!
  • Cara Dapat Kode Kartu Hadiah Netflix Gratis Tanpa Ribet
  • Inilah Caranya Dapet Bukti Setor Zakat Resmi dari NU-Care LazisNU Buat Potong Pajak di Coretax!
  • Inilah 10 Jurusan Terfavorit di Universitas Brawijaya Buat SNBT 2026, Saingannya Ketat Banget!
  • Inilah Cara Terbaru Login dan Ubah Password Akun PTK di EMIS GTK IMP 2026
  • How to Remove Underlines from Links in Outlook
  •  How to Fix Microsoft 365 Deployment Tool Not Working: A Complete Troubleshooting Guide
  •  How to Fix Windows 11 ISO Download Blocked and Error Messages
  • How to Make Your Website Vibrate with Web Haptics
  • Measuring LLM Bullshit Benchmark
  • How to Launching Production-Ready Agents with Google Antigravity and AI Studio
  • How to Automate Your Business Intelligence with Google Antigravity and NotebookLM
  • The Secret Reason Seedance 2.0 is Realistic
  • Exploring Microsoft Phi-4 Reasoning Vision 15B
  • Gemini 3.1 Flash-Lite Released: How to Master Google’s Fastest AI Model for Real-World Projects
  • Apa itu Spear-Phishing via npm? Ini Pengertian dan Cara Kerjanya yang Makin Licin
  • Apa Itu Predator Spyware? Ini Pengertian dan Kontroversi Penghapusan Sanksinya
  • Mengenal Apa itu TONESHELL: Backdoor Berbahaya dari Kelompok Mustang Panda
  • Siapa itu Kelompok Hacker Silver Fox?
  • Apa itu CVE-2025-52691 SmarterMail? Celah Keamanan Paling Berbahaya Tahun 2025
Beli Morning Star Kursi Gaming/Kantor disini: https://s.shopee.co.id/805iTUOPRV
Beli Pemotong Rumput dengan Baterai IRONHOOF 588V Mesin Potong Rumput 88V disini https://s.shopee.co.id/70DBGTHtuJ

©2026 emka.web.id | Design: Newspaperly WordPress Theme