In PHP, how can I get the first two and last two characters of a string without using string or array functions?

✅ Solution:

You can use preg_replace to keep only the first two letters of each word while removing the rest.


<?php
$str = 'Mukesh Dubey';
$output = preg_replace("/([A-Z][a-z])\S+/", "$1", $str);
echo $str . "\n" . $output; 
// Output:
// Mukesh Dubey
// Mu Du
?>

The regex ([A-Z][a-z])\S+ matches:

([A-Z][a-z]) → one uppercase followed by one lowercase letter (captured).

\S+ → all the following non-space characters (discarded).

$1 keeps only the captured two letters.


<?php
$str = 'wolly dolly';
$output = preg_replace("/([A-Za-z]{2})\S+/", "$1", $str);
echo $str . "\n" . $output;
// Output:
// wolly dolly
// wo do
?>

This variant keeps the first two alphabetic characters of every word, regardless of case.