Created
April 29, 2021 22:37
-
-
Save fadhil-riyanto/60d37a54573b70a0fe92df7a90e298be to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function rampingkan_text($string, $type) | |
{ | |
//PERTAMA cek kondisi dia milih type rampingkan apanya | |
if($type == "NEW_LINE"){ | |
$ipes = PHP_EOL; | |
}elseif($type == "SPACE"){ | |
$ipes = " "; | |
}elseif($type == "KOMA"){ | |
$ipes = ","; | |
}elseif($type == "TITIK"){ | |
$ipes = "."; | |
}elseif($type == "NEW_LINE_SPACE"){ | |
$ipes = PHP_EOL . " "; | |
} | |
//ambil inputan nya | |
$inp = $string; | |
//lalu explode berdasar spasi | |
$exp = explode($ipes, $inp); | |
//inisialisiasi index dulu, buat nyebut array nya | |
$index = 0; | |
//lalu hasil explode di foreach | |
foreach ($exp as $ee) { | |
//algoritma : jika kata index pertama itu sama | |
//dengan kata index yang ditambah 1 | |
//jika ditemukan kesamaan dengan kata pertama | |
//dengan index maju 1 langkah kedepan, maka ganti null | |
if ($ee == @$exp[$index + 1]) { | |
$ee = null; | |
} | |
//ini default, ini akan menampunng semua kata | |
//hasil pengosongan if else dan foreach tadi | |
$ress[] = $ee; | |
//ini counter buat nunjuk array | |
$index = $index + 1; | |
} | |
//lalu implode, berdasar spasi | |
$mentah = implode(' ', $ress); | |
//hapus spasi yang kebanyaan | |
$regex = preg_replace('/\s+/', ' ', $mentah); | |
//hapus spasi didepan string | |
return ltrim($regex); | |
} | |
//test | |
$subjek_contoh = "kucing | |
mumu | |
bulat | |
meong | |
meong | |
nyan | |
cat"; | |
echo rampingkan_text($subjek_contoh, "NEW_LINE"); | |
//parameter pertama subjek, bisa diambil dari mana aja, misal text area | |
//kedua adaah type perampingan, bisa dikasi plihan pake dropdown di web nya | |
//result | |
//kucing mumu bulat meong nyan cat | |
//Note : ada error e_notice kan? btw itu aman kok, | |
//karna apa? pas penunjukan index tadi. kan +1 | |
//jika kita punya array 7, maka di looping nya akan menjadi 8, | |
//nah, karna pas di if else, agka 8 gaada, maka dia error notice | |
//gpp sih, kan dia cuma error kelebihan array, dan array itu ga kita pake... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment