Reputation: 356
I have a specific condition where I need to replace every instance of a "ct" with "c-t" provided there is a consonant before 'c' and a vowel after 't'. I am unable to do so :
<?php
$string = "october solatrix regnum sanctus sanctus";
echo constantCT($string);
function constantCT($string)
{
$arr1 = str_split($string);
$length = count($arr1);
$pc=0;
for($j=0;$j<$length;$j++)
{
$check = $arr1[$j+1].$arr1[$j+2];
if($check=='ct')
{
$pc++;
}
}
function strAppend4($string)
{
$arr1 = str_split($string);
$length = count($arr1);
for($z=0;$z<$length;$z++)
{
$check = $arr1[$z+1].$arr1[$z+2];
if($check == 'ct')
{
//echo "ct found <br>";
//echo $arr1[$z]; echo "<br>";
//echo $arr1[$z+3]; echo "<br>";
$verifyC = isConstant($arr1[$z]);
$verifyV = isVowel($arr1[$z+3]);
if($verifyV && $verifyC)
{
echo $z+2;
$updatedString = substr_replace($string, "-", $z+2,0);
//echo $updatedString;
return $updatedString;
}
}
else
{
//echo "ct not found <br>";
}
}
}
$st1 = $string;
for($k=0;$k<$pc;$k++)
{
$st1 = strAppend4($st1);
}
return $st1;
}
So I should get the output as :
october solatrix regnum sanc-tus sanc-tus
The ct
in october
should not be tampered with as before 'c' there is a vowel and not a consonant.
Upvotes: 2
Views: 134
Reputation: 23880
You can do this with a regex using character classes.
echo preg_replace('/([^aeiou]c)(t[aeiou])/', '$1-$2', 'october solatrix regnum sanctus sanctus');
PHP Demo: https://eval.in/659567
Regex101: https://regex101.com/r/Nqiaav/1
or with a stricter character class:
echo preg_replace('/([b-df-hj-np-tv-xz]c)(t[aeiouy])/', '$1-$2', 'october solatrix regnum sanctus sanctus');
https://regex101.com/r/Nqiaav/2 (can add/remove y
if that isn't a vowel)
Also this assumes you only wanted lowercase, if you want to allow upper case as well use the i
modifier, or add all capitals to the character classes.
Upvotes: 4
Reputation: 316
Try this:
for($j=0;$j<strlen($string);$j++)
{
if($string[$j] == 'c' && $string[$j+1] == 't')
{
substr_replace($string, '-', $j+1, 0);
$j += 2;
}
}
echo $string;
Upvotes: 0