Skip to content

Instantly share code, notes, and snippets.

@isfaaghyth
Last active February 3, 2020 17:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save isfaaghyth/07582864a5c504de177a92ab8ca7729e to your computer and use it in GitHub Desktop.
Save isfaaghyth/07582864a5c504de177a92ab8ca7729e to your computer and use it in GitHub Desktop.
Split Name, Birth, and Born with PHP
<?php
/*
apply for : Isfahani Ghiyath 24 Makassar or,
Isfahani Ghiyath 24 Th Makassar or,
Isfahani Ghiyath 24 Tahun Makassar or,
Isfahani Ghiyath 24 Tahun Sulawesi Selatan.
*/
$test = "Isfahani Ghiyath 24 Tahun Makassar";
//Mengambil string sebelum angka. Dapat angkanya dari fungsi ambilUmur();
echo "Nama : " . ambilSebelum($test, ambilUmur($test)) . "<br>";
//Mendapatkan angka menggunakan fungsi ambilUmur();
echo "Umur : " . ambilUmur($test) . "<br>";
//Mengambil string setelah angka.
$kota = ambilSetelah($test, ambilUmur($test));
//variable $kota kemungkinan mengandung string "Tahun" atau "Th", jadi {1} dan {2}
if (preg_match('/Th/', $kota)) {
//{1} Ambil string setelah Th
//str_replace berfungsi untuk menghilangkan spasi
$kota = ambilSetelah(str_replace(' ', '', $kota), "Th");
} elseif (preg_match('/Tahun/', $kota)) {
//{2} Ambil string setelah Tahun
//str_replace berfungsi untuk menghilangkan spasi
$kota = ambilSetelah(str_replace(' ', '', $kota), "Tahun");
}
//Tampilkan kota yang sudah di split.
//preg_replace berfungsi untuk menambahkan spasi antara string yang berkapital,
//(bermanfaat kalau nama kotanya lebih dari 1 kata)
echo "Kota : " . preg_replace('/(?<!\ )[A-Z]/', ' $0', $kota) . "<br>";
//Ambil umur (0-9)
function ambilUmur($konten) {
return preg_replace('/[^0-9]/', '', $konten);
}
//ambil string setelah: dengan 2 param, param pertama untuk string yang akan displit, dan
//param kedua sebagai string acuan yang akan dipotong.
function ambilSetelah($string, $substring) {
$pos = strpos($string, $substring);
if ($pos === false) {
return $string;
} else {
return(substr($string, $pos+strlen($substring)));
}
}
//ambil string sebelum: dengan 2 param, param pertama untuk string yang akan displit, dan
//param kedua sebagai string acuan yang akan dipotong.
function ambilSebelum($string, $substring) {
$pos = strpos($string, $substring);
if ($pos === false) {
return $string;
} else {
return(substr($string, 0, $pos));
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment