Skip to content

emka.web.id

menulis pengetahuan – merekam peradaban

Menu
  • Home
  • Tutorial
  • Search
Menu

PHP Cookbook: Replacing Substrings

Posted on December 15, 2011

Problem
You want to replace a substring with a different string. For example, you want to obscure all but the last four digits of a credit card number before printing it.

Solution
Use substr_replace(), as in Example 1-15.
Example 1-15. Replacing a substring with substr_replace( )
[sourcecode language=”php”]
// Everything from position $start to the end of $old_string
// becomes $new_substring
$new_string = substr_replace($old_string,$new_substring,$start);
// $length characters, starting at position $start, become $new_substring
$new_string = substr_replace($old_string,$new_substring,$start,$length);
[/sourcecode]

Discussion
Without the $length argument, substr_replace( ) replaces everything from $start to the end of the string. If $length is specified, only that many characters are replaced:
[sourcecode language=”php”]
print substr_replace(‘My pet is a blue dog.’,’fish.’,12);
print substr_replace(‘My pet is a blue dog.’,’green’,12,4);
$credit_card = ‘4111 1111 1111 1111’;
print substr_replace($credit_card,’xxxx ‘,0,strlen($credit_card)-4);
[/sourcecode]
[sourcecode]
My pet is a fish.
My pet is a green dog.
xxxx 1111
[/sourcecode]

If $start is negative, the new substring is placed at $start characters counting from the end of $old_string, not from the beginning:
[sourcecode language=”php”]
print substr_replace(‘My pet is a blue dog.’,’fish.’,-9);
print substr_replace(‘My pet is a blue dog.’,’green’,-9,4);
[/sourcecode]
[sourcecode]
My pet is a fish.
My pet is a green dog.
[/sourcecode]

If $start and $length are 0, the new substring is inserted at the start of $old_string:
print substr_replace('My pet is a blue dog.','Title: ',0,0);
Title: My pet is a blue dog.

The function substr_replace( ) is useful when you’ve got text that’s too big to display all at once, and you want to display some of the text with a link to the rest. Example 1-16 displays the first 25 characters of a message with an ellipsis after it as a link to a page that displays more text.

Example 1-16. Displaying long text with an ellipsis
[sourcecode language=”php”]
$r = mysql_query("SELECT id,message FROM messages WHERE id = $id") or die();
$ob = mysql_fetch_object($r);
printf(‘<a href="more-text.php?id=%d">%s</a>’,
$ob->id, substr_replace($ob->message,’ …’,25));
[/sourcecode]

The more-text.php page referenced in Example 1-16 can use the message ID passed in the query string to retrieve the full message and display it.

See Also
Documentation on substr_replace( ) at http://www.php.net/substr-replace.

Terbaru

  • Inilah Caranya Mengajar Bahasa Indonesia di Amerika Serikat Lewat Beasiswa Fulbright FLTA 2026
  • Inilah 6 Rekomendasi HP yang Awet dan Tahan Lama Biar Kalian Nggak Gonta-ganti Terus!
  • Apa itu Proses BOP dan Psikotes BRI Life?
  • Ini Cara Input Tugas Tambahan Guru di EMIS GTK IMP 2026 Biar Jam Mengajar Aman!
  • APK Juice Pack Frenzy Penipuan? Benarkah Membayar atau Cuma Tipuan Iklan? Ini Faktanya!
  • Apakah Apk ReelAct Penipu? Mau Tarik 100 Dolar dari Reel Act? Cek Dulu Faktanya Biar Nggak Rugi Waktu!
  • Inilah Rekomendasi Game Turn Base Android dan PC Terbaik Buat Kalian yang Suka Strategi!
  • Inilah Cara Membuat Sertifikat di Canva dan Ukuran Standar yang Wajib Kalian Tahu
  • Inilah Aturan Zakat yang Bisa Jadi Pengurang Pajak Bruto Kalian, Sudah Tahu Belum?
  • Inilah Data Pendaftar KIP Kuliah 2026 Jalur SNBP dan Bocoran Kriteria yang Lolos!
  • Inilah Game Silent Hill: Townfall, Teror Psikologis Baru yang Bakal Bikin Kalian Gemetar di Tahun 2026!
  • Inilah Trailer Mortal Kombat 2, Johnny Cage Resmi Gabung dan Siap Hadapi Shao Kahn!
  • Inilah Spesifikasi Lengkap Samsung Galaxy S26 yang Baru Meluncur, Ternyata Harganya Naik Segini!
  • Inilah Cara Mematikan MSA Xiaomi Supaya HP Nggak Lemot dan Bebas Iklan, Ternyata Langkahnya Simpel Banget!
  • Inilah Kronologi Mobil Calya Plat D yang Viral Lawan Arus di Jakpus, Ternyata Bawa Banyak Plat Palsu!
  • Inilah Axioo Hype AI 5, Laptop AI Canggih yang Nggak Bikin Kantong Bolong!
  • Ini Loh Kejahatan Modus Phishing Google Tasks Terbaru yang Bisa Nguras Data Perusahaan Kalian
  • Inilah Poco X7 5G dan M7 Pro 5G, HP Gaming Performa Ekstrem yang Ngebikin Mabar Kalian Jadi Anti Lag!
  • Inilah Cara Mengubah Lahan Kosong Jadi Uang Lewat Strategi Land Banking
  • Ini Trik Supaya Gajian YouTube Shorts Tembus Puluhan Juta dari Penonton Bule!
  • Jangan Sampai Keliru! Begini Cara Cek Total Jam Linear dan Non Linear di EMIS GTK IMP 2026
  • Cuma Nonton Drama Pendek Bisa Cair Uang Tunai? Bongkar Habis Kebenaran Aplikasi FunFlick di Sini!
  • Apa itu Resetter Epson L3210?
  • Ini Loh Ukuran A4, F4, A3, B5, A5 di Canva Biar Hasil Cetakan Kalian Nggak Terpotong!
  • Inilah Cara Transfer Pulsa Telkomsel Paling Update 2026, Lengkap dengan Biaya dan Syarat Terbarunya!
  • Inilah Xolo.io, Solusi Praktis Buat Kalian yang Pengen Bangun Startup Skala Global Tanpa Harus Pindah ke Luar Negeri
  • Inilah Caranya Lapor SPT Tahunan Lewat Coretax Supaya Nggak Kena Denda
  • Inilah Alasan Kenapa Software House Lokal Susah Dapat Insentif Pajak R&D dan Isu Amortisasi Pegawai yang Bikin Pusing
  • Inilah Alasan Kenapa Developer Game Indonesia Lagi Curhat Soal Pajak: Kasus Toge Productions
  • Inilah Alasan Ilmiah Kenapa Lampu Lalu Lintas Pakai Warna Merah, Kuning, dan Hijau!
  • How to Fix Error Code 0x80073d21 for Enhanced Speech Recognition on Windows
  • What is DNS-Persist-01? Let’s Encrypt’s New Solution for Reliable SSL Validation
  • How to Use User Accounts & System Admin on Linux Mint 23
  • What is Docker Digest Watching? Understanding the New Standard in Docker 8.2
  • What is LibreOffice Online? A Guide to the Community-Driven Cloud Office Suite
  • Prompt AI Menyusun Script Pola Suara Karakter agar Brand Jadi Ikonik
  • Prompt AI untuk Merancang Karakter Brand yang Ikonik
  • Prompt AI Audit Konten Sesuai Karakter Brand
  • Prompt AI Merubah Postingan LinkedIn Jadi Ladang Diskusi dengan ChatGPT
  • Prompt AI: Paksa Algoritma LinkedIn Promosikan Konten Kalian
  • 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 Pemotong Rumput dengan Baterai IRONHOOF 588V Mesin Potong Rumput 88V disini https://s.shopee.co.id/70DBGTHtuJ
Beli Morning Star Kursi Gaming/Kantor disini: https://s.shopee.co.id/805iTUOPRV

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