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 Daftar Manajer Koperasi Merah Putih, Peluang Karir BUMN dengan 30.000 Formasi
  • Inilah 5 Rekomendasi Bedak Two Way Cake Anti Oksidasi Supaya Wajah Nggak Terlihat Kusam dan Gelap
  • Inilah Syarat dan Cara Mengurus Surat Sehat Jasmani Rohani untuk Daftar Manajer Kopdes Merah Putih
  • Inilah Alasan Harga Plastik Naik dan 7 Alternatif Kemasan Ramah Lingkungan yang Lebih Hemat buat UMKM
  • Inilah Profil Syekh Ahmad Al Misry dan Rekam Jejaknya yang Sedang Viral di Media Sosial
  • Inilah Alasan HP Nokia Jadul Harganya Masih Selangit dan Banyak Diburu Kolektor di Tahun 2026
  • Inilah HP Samsung A Series Terbaru yang Pakai Layar AMOLED, Mewah Tapi Harganya Terjangkau Banget!
  • Inilah Vivo T5 Pro, HP Midrange dengan Baterai 9.020 mAh yang Siap Comeback ke Indonesia!
  • Inilah Cara Daftar Manajer Koperasi Desa Merah Putih 2026, Ada 30.000 Formasi yang Bisa Kalian Lamar!
  • Inilah Alasan Kenapa Kemkomdigi Ancam Blokir Wikipedia dan Dampak Seriusnya Buat Masa Depan Pendidikan Kita
  • Inilah Cara Cek BLT Desa 2026 Tahap 2, Cair Rp900 Ribu Langsung ke Tangan Kalian!
  • Inilah Cara Cek PIP Lewat HP 2026 dan Panduan Lengkap Pencairannya Biar Dana Nggak Hangus
  • Inilah 51 Kode Redeem FF Aktif 17 April 2026, Buruan Klaim Skin Blue Angelic dan Bundle Langka!
  • Inilah Huawei Mate 80 Pro, Sang Legenda Flagship yang Kembali dengan Kamera True-to-Colour dan Ketahanan Luar Biasa
  • Inilah Deretan iPhone Terlawas yang Masih Layak Dibeli Tahun 2026, Performa Tetap Ngebut dan Harga Terjangkau!
  • Inilah HP Oppo Paling Worth It di Tahun 2026, Spesifikasi Gahar Tapi Harga Tetap Merakyat!
  • Inilah Daftar Link Nonton Film Ilegal yang Diblokir Komdigi dan Alasan Kenapa Kalian Harus Waspada
  • Inilah Lenovo Legion Y70 (2026), HP Gaming yang Siap Guncang Pasar dengan Teknologi AI
  • Inilah Rekomendasi HP Oppo Murah Spek Mewah Tahun 2026 yang Nggak Bakal Bikin Kantong Kalian Jebol!
  • Inilah 15 Situs Nonton Film Gratis Legal 2026, Bye-Bye Iklan Ganggu dan Drama Situs Ilegal!
  • Inilah Beasiswa Bekraf Digital Talent 2026: Solusi Buat Kalian yang Mau Jago AI dan Makin Produktif
  • Inilah Cara Memilih Power Bank yang Aman Dibawa ke Pesawat Agar Tidak Disita Petugas
  • Inilah Bocoran Harga dan Spesifikasi Redmi K90 Max, HP Gaming Dimensity 9500 Termurah yang Segera Dirilis!
  • Inilah RedMagic Gaming Tablet 5 Pro, Monster Gaming dengan Layar 185Hz dan Chipset Snapdragon 8 Elite yang Bikin Melongo!
  • Inilah Kenapa IGRS Trending di X, Bocorkan Spoiler Penting Game 007 First Light Hingga Ending!
  • Inilah 5 HP Murah Terbaru dengan Baterai Jumbo yang Siap Masuk Indonesia 2026, Ada yang Sampai 7.800 mAh!
  • Inilah Alasan Kenapa Samsung Galaxy S27 Bakal Pakai 50 Persen Chipset Exynos, Qualcomm Mulai Ditinggalkan?
  • Inilah Vivo Y31d Pro, Smartphone “Badak” dengan Baterai 7000mAh dan Ketahanan Standar Militer
  • Inilah 11 Game Penghasil Saldo DANA Tercepat 2026, Cara Asyik Cari Cuan Sambil Rebahan!
  • Inilah Motorola Edge 70 Pro, HP Midrange Gahar dengan Baterai 6500 mAh yang Siap Meluncur!
  • Is it Time to Replace Nano? Discover Fresh, the Terminal Text Editor You Actually Want to Use
  • 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 use the Wan 2.7 AI model: A complete walkthrough
  • How to Run Minimax M2-7 Locally: A Step-by-Step Guide for Beginners
  • How to Build Self-Driving Codebases with Async Agents and NVIDIA Hardware
  • How to create a professional AI influencer using Apob AI
  • How to Use AI-Powered Tools to Level Up Your Stock Market Research Game with Claude Code
  • New Text Document
  • 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?

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