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

  • Penyebab Aplikasi Wondr BNI Tidak Bisa Dibuka
  • Kode 0425 Daerah Mana? Ini Pengertian dan Fakta Sebenarnya
  • Apa Itu SSS CapCut? Pengertian Downloader Video Tanpa Watermark yang Wajib Kalian Tahu
  • Apa Itu Paket GamesMAX Telkomsel? Ini Pengertian dan Fungsinya Bagi Gamers
  • Apa Itu Menu Plus di Google Search? Ini Pengertian dan Fungsinya
  • Apa Itu Lepas Kolpri? Ini Pengertian dan Fenomenanya di Dunia Gaming
  • Pixel Buds Pro Dapat Update Software dengan Dukungan ANC Adaptif dan Peningkatan Audio
  • Mous Pixel Watch 4 Akan Hadir dengan Charger Baru dan Fitur-Fitur Terbaru
  • Hati-hati, Video Asli Botol Golda Viral Season 4 Full 6.30 Menit, Cek Link dan Faktanya disini!
  • Google Docs Dapat Update Material 3 dan Desain Ekspresif Baru, Fokus pada Kreativitas dan Kolaborasi
  • Belum Tahu? Ini Trik Hitung Cost Per Gigabyte Supaya Gak Boncos Saat Beli Paket Internet
  • Apple TV dan Google Cast Akan Terintegrasi Lebih Dalam, Tawarkan Pengalaman Streaming yang Lebih Baik
  • Lagi Rame Botol Golda Viral 19 Detik? APA ITU? Jangan Asal Klik Link Sembarangan, Ini Bahayanya!
  • Apa itu Regedit FF Auto Headshot 100 No Password 2024? Simak Definisi dan Cara Kerjanya
  • Apa Itu KPH dan MPH? Pengertian dan Perbedaannya di Game Balap
  • Belum Tahu? Inilah Cara Aman Quotex Login dan Solusi Kalau Error!
  • Apa Itu Fitur Gestur Baru di Pixel Watch 4? Ini Pengertian dan Perbedaannya
  • Belum Tahu? Inilah Cara Aman Login Binomo dan Trik Trading Buat Pemula Biar Nggak Boncos
  • Cara Mengatasi Error ‘Versi Diagnostik Belum Terbarui’ (Your current version of diagnostics is not up to date)
  • Cara Membuat Newsletter di Outlook 365
  • Sering Telepon di Tempat Berisik? Fitur Baru Expressive Call dari Google Bakal Jadi Penyelamat Kalian!
  • Google Pixel 10 Pro Akan Punya Integrasi Play Points Lebih Dalam
  • Stop Cara Kuno! Ini Trik Supaya Manajemen Karyawan Jadi Lebih Cepat dan Anti Ribet
  • Bug di Aplikasi Cuaca Wear OS Google: Update Tidak Ngaruh!
  • Samsung Kembangkan Sensor Kamera Baru Pakai Teknologi Global Shutter dan Efek Blur Bergerak
  • Cara Membuat Anggaran Otomatis di Excel
  • Baseus X1 Pro Kamera: Kamera Ringkas dengan Fitur Canggih dan Harga yang Menarik
  • Profil Sosmed Kalian Sepi? Gini Caranya Makeover Bio Biar Makin Dilirik Sama Netizen!
  • Cara Mengatasi Error ‘Disk is Full or Read-Only’
  • Belum Tahu? Inilah Trik Ampuh Atasi Error ‘We Were Unable To Create Your Notebook’ di OneNote
  • Ini Dia ESP32 P4: IoT RISC-V dengan Layar AMOLED dan LoRa, Perangkat Handheld Inovatif
  • Apa Itu HealthyPi-6? Solusi Open Source untuk Akuisisi Biosignal
  • Jetson THOR Industrial PC: 25Gbe Networking dan Bisa Pakai Kamera GMSL2
  • Azul Systems Akuisisi Payara Java Server
  • PC Kentang Jadi Ngebut? Coba GRML 2025, Distro Debian Ringan dengan Kernel 6.17!
  • Apa Itu US National Framework for AI? Kepres Donald Trump Bikin Heboh Dunia AI
  • Kenapa Bisnis Properti & Real Estate Harus Pakai AI, Ini Alasannya!
  • BARU! Brave Browser Bakal Bisa Ngerjain Tugas Kalian Secara Otomatis Lewat Agentic AI!
  • Belum Tahu? Google Maps Bakal Makin Canggih Berkat Integrasi Gemini Visual Ini!
  • Siap-Siap! Tahun 2026 Gemini Bakal “Menjajah” Chrome, iPhone, sampai Smartwatch Kalian
  • Apa Itu Video PT Pabrik Brebes Viral? Ini Pengertian dan Fakta Sebenarnya
  • Apa itu Data Breach Coupang? Pengertian dan Kronologi Kebocoran Data Terbesar di Korea Selatan
  • Apa Itu CVE-2018-4063? Pengertian Celah Keamanan Sierra Wireless AirLink yang Masuk Katalog CISA
  • Apa Itu Ashen Lepus? Kelompok Peretas yang Mengincar Instansi Pemerintah Timur Tengah
  • Pengertian Vulnerability WebKit Apple Terbaru: Apa Itu CVE-2025-43529 dan CVE-2025-14174?

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