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 Cara Dapat Saldo Cool Lady Tanpa Undang Teman, Ternyata Begini Trik Rahasianya!
  • Inilah Cara Main Watermelon Merge Fun Biar Dapat Saldo DANA, Apakah Benaran Membayar?
  • Inilah Kenapa Stok Penarikan Free Reels Sering Habis dan Cara Mengatasinya Agar Saldo Cair!
  • Inilah Alasan Kenapa Telat Lapor SPT 2026 Nggak Bakal Kena Denda, Cek Aturan Lengkapnya!
  • Inilah Cara Mematikan Koreksi Otomatis di WhatsApp Agar Nggak Salah Ketik Lagi
  • Apa itu Bujang Inam? Inilah Alasan Kenapa Kata Ini Jadi Makian Paling Kasar dalam Budaya Medan dan Batak!
  • Inilah Kenapa Link FF Kipas My ID Verify UID Beta Testing Sering Gagal dan Cara Menghadapinya
  • Gini Caranya Mulai Dropshipping Pake AI di Tahun 2026, Auto Cuan Tanpa Ribet!
  • Baterai Smartwatch Boros? Inilah Caranya Biar Baterai Smartwatch Kalian Bisa Awet Berhari-hari!
  • Belum Tahu? Inilah Fakta Cahaya Misterius di Lampung yang Ternyata Sampah Roket China CZ-3B!
  • Inilah Roblox Mod APK 2026, Fitur Premium Jadi Gratis dan Cara Pasangnya yang Perlu Kalian Tahu!
  • Inilah Panduan Lengkap UTUL UGM 2026, Cari Tahu Jadwal, Biaya Pendaftaran, Sampai Info Uang Pangkal IPI di Sini!
  • Inilah IGRS di Roblox dan Steam, Ternyata Ini Alasan Komdigi Kasih Aturan Ketat!
  • Inilah Makna Mendalam Regina Caeli: Kenapa Umat Katolik Wajib Doa Ratu Surga Selama Masa Paskah?
  • Inilah Kronologi Lengkap Kecelakaan Truk TNI di Kalideres: Simak Fakta dan Status Sopirnya Sekarang!
  • Inilah Rahasia Ambil Ide Youtube Lain, Tapi Konten Kalian Nggak Terlihat Membosankan
  • Studi Kasus SEO: Ellevest Dapat 14 Ribu Pengunjung Organik Per Bulan dengan Strategi SEO Niche dan Otomasi AI
  • Inilah Rahasia ReciMe, Potensi Sukses dari Aplikasi Resep Sederhana
  • Perkuat Kemandirian Industri Alat Kesehatan Nasional, Astra Komponen Indonesia Hadirkan Alat Kesehatan Berbasis Teknologi Digital
  • Vidrush, Solusi Produksi Video massal buat Channel Faceless
  • Inilah Higgsfield AI Audio, Trik Canggih Buat Voice Cloning dan Dubbing Video Youtube Otomatis!
  • Everything You Need to Know About Project X and the Rumored AI-Powered Remaster of The Sims 4
  • Inilah Trik Cuan dari Instagram Jadi Affiliator, Tapi Tanpa Perlu Jualan Produk!
  • Inilah 7 Ide Channel YouTube Aneh Tapi Sederhana yang Bisa Kalian Mulai Sekarang Juga!
  • Apa itu Umroh & Keutamaannya: Inspirasi dari pergiumroh.com
  • Belum Tahu? Gini Caranya Dapat Bisnis Sukses Cuma dari Clipping Video Pake AI
  • Inilah Rahasia Perbaiki Algoritma Video YouTube yang Mulai Sepi
  • Kenapa Cicilan di Bank Syariah Itu Tetap?
  • Inilah 7 Produk Digital Paling Realistis untuk Kalian yang Mau Jualan Online Tahun Ini!
  • Inilah 4 Strategi Memilih Niche SEO Terbaik Supaya Blog Kalian Cepat Ranking
  • How to Design a Services Like Google Ads
  • How to Fix 0x800ccc0b Outlook Error: Step-by-Step Guide for Beginners
  • How to Fix NVIDIA App Error on Windows 11: Simple Guide
  • How to Fix Excel Formula Errors: Quick Fixes for #NAME
  • How to Clear Copilot Memory in Windows 11 Step by Step
  • How to Use Orbax Checkpointing with Keras and JAX for Robust Training
  • How to Automate Any PDF Form Using the Power of Manus AI
  • How to Training Your Own YOLO26 Object Detection Model!
  • How to Build a Full-Stack Mobile App in Minutes with YouWare AI
  • How to Create Consistent Characters and Cinematic AI Video Production with Seedance
  • 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

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