String replace to certain format

May I know how to use string replace to a certain symbols in the character with follow the format?

Below is example what I want the results, I just want to replace in front number inside the symbols:

Before                                                  |     After (Expected result)
100-1-1 Penggubalan/Penyediaan/Pindaan Undang-Undang        100-1/1 Penggubalan/Penyediaan/Pindaan Undang-Undang
100-1-1-16 Undang-Undang Kecil Hotel/test                   100-1/1/16 Undang-Undang Kecil Hotel/test

Format inside number with symbol need to change, XXX is fixed number total format,() is random number total format:

xxx-()-()      change to  xxx-()/()
xxx-()-()-()   change to  xxx-()/()/()

Below is I've tried the coding:

$try = "100-1-1 Penggubalan/Penyediaan/Pindaan Undang-Undang";
$try_1 = "100-1-1-16 Undang-Undang Kecil Hotel/test";
$test = str_replace('-','/',trim($try));
$test_2 = str_replace('-','/',trim($try_2));

echo $test;
echo $test_2;

Upvotes: 0

Views: 110

Answers (1)

Debargha Roy
Debargha Roy

Reputation: 2708

Below is a very naive approach, but it works.

<?php 
function replaceHyphen($str) {
    $i = -1;
    for($i=0; $i < strlen($str); $i++) {
        if($str[$i] == "-") break;
    }
    for($i++; $i < strlen($str); $i++) {
        if($str[$i] == "-") $str[$i] = '/';
        if($str[$i] == " ") break;
    }
    return $str;
}
$try = "100-1-1 Penggubalan/Penyediaan/Pindaan Undang-Undang";
$try_1 = "100-1-1-16 Undang-Undang Kecil Hotel/test";

echo(replaceHyphen($try));
echo(replaceHyphen($try_1));
?>

Upvotes: 0

Related Questions