<?php
function inject_hyphens($word, $positions)
{
$pad = 0;
foreach ($positions as $position)
{
$word = substr($word, 0, $position + $pad) . '-' . substr($word, $position + $pad, strlen($word));
$pad++;
}
return $word;
}
$input = array('syl-labification',
'sylla-bification',
'syllabi-fication',
'syllabifi-cation',
'syllabifica-tion',
'syllabification'
);
//wanted $output = 'syl-la-bi-fi-ca-tion';
$positions = array();
foreach($input as $word)
{
preg_match_all('/-/', $word, $matches, PREG_OFFSET_CAPTURE);
foreach($matches[0] as $key => $value)
{
$positions[] = $value[1];
}
}
$positions = array_unique($positions);
var_dump(inject_hyphens('syllabification', $positions));
preferences:
39.09 ms | 402 KiB | 5 Q