Search code examples
phpregexstringcharactertext-extraction

Build a new string from every nth character of a string


I have a long string from which I need to get every 12th character. I currently do it with a for() loop, but I'm wondering if there is a better/more efficient way.

$verylongstring = 'thisisalongstringwithawholelotofcharctersitgoesonforawhile...loremipsum'; 
$newstring = '';

for ($i = 0; $i < strlen($verylongstring); $i++) 
{ 
    if ($i % 12 == 0) {
        $newstring .= $verylongstring[$i];
    }
} 
echo $newstring;

Solution

  • A little preg_replace() should work for you -

    $verylongstring='thisisalongstringwithawholelotofcharctersitgoesonforawhileloremipsum'; 
    $newString = preg_replace('/(.).{11,11}/', '$1', $verylongstring);
    echo $newString;
    

    Here is an example - http://phpfiddle.org/main/code/gf4i-6221