user1343099
user1343099

Reputation: 49

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;

Upvotes: 0

Views: 1034

Answers (2)

mickmackusa
mickmackusa

Reputation: 47992

Match the first eleven characters then capture the twelfth character; if this subpattern is satisfied, replace all twelve chatacters with the twelfth character. Otherwise, match the remainder of the string (eleven characters or less) and replace those characters with an empty string (the unpopulated first capture group).

Code: (Demo)

echo preg_replace('/.{11}(.)|.*/', '$1', $verylongstring);
// shroo

Or without alternation, greedily match upto eleven characters (not giving back), then capture the twelfth character if it exists. Demo

echo preg_replace('/.{1,11}(.?)/', '$1', $verylongstring);

Upvotes: 0

Jay Blanchard
Jay Blanchard

Reputation: 34426

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

Upvotes: 0

Related Questions