How to remove N characters from the middle of a string in PHP

1 Answer

0 votes
function removeMiddleChars($string, $n) {
    $length = strlen($string);
    $start = ($length - $n) / 2;

    return substr_replace($string, '', $start, $n);
}

$str = "abc123def";
$N = 3;
$result = removeMiddleChars($str, $N);

echo $result; 


/*
run:

abcdef

*/

 



answered Sep 11, 2024 by avibootz
edited Apr 19, 2025 by avibootz
...