This task only requires one function call. The preg_replace()
match non-dot substrings then dots $n-1
times, then on the nth occurrence it will handle the targeted dot.
Assuming these variables:
$n=4;
$strings=["First. Second.Third.",
"First. Second.Third. Fourth.",
"First. Second. Third. Fourth. Fifth.",
"First. Second.Third. Fourth. Fifth. Sixth. Seventh. Eighth."
];
Method #1
(Keep everything except for the 4th dot): (Demo) (Regex Pattern/Replacement Demo)
$strings=preg_replace('/((?:[^.]*?\.){'.($n-1).'}[^.]*)\.(.*)/','$1$2',$strings);
var_export($strings);
Output:
array (
0 => 'First. Second.Third.',
1 => 'First. Second.Third. Fourth',
2 => 'First. Second. Third. Fourth Fifth.',
3 => 'First. Second.Third. Fourth Fifth. Sixth. Seventh. Eighth.',
)
Method #2
(Replace only the 4th dot with an empty string) (Demo) (Regex Pattern/Replacement Demo)
$strings=preg_replace('/(?:[^.]*\.){'.($n-1).'}[^.]*?\K\./','',$strings,1); // note the last parameter `1` so that it doesn't match the eighth dot
var_export($strings);
// same results as first method
The above methods will work the same on your input string as it does on my array of strings.
$n=4;
$string="My name is Resheil. I'm developing in PHP. I have used mysql for my application. I want to replace the full stop on the nth position in php.";
$string=preg_replace('/((?:[^.]*?\.){'.($n-1).'}[^.]*)\.(.*)/','$1$2',$string);
echo $string;
// or
$string=preg_replace('/(?:[^.]*\.){'.($n-1).'}[^.]*?\K\./','',$string,1);
echo $string;
// output:
// My name is Resheil. I'm developing in PHP. I have used mysql for my application. I want to replace the full stop on the nth position in php
If you'd like to see a non-regex method, this works by "bumping right" the starting point of strpos()
on each iteration of the for
loop. If the process locates a 4th dot, it displays the two substrings on either side of it. If no 4th dot is found, the full string is displayed.
Method #3
(Demo)
$n=4;
$string="My name is Resheil. I'm developing in PHP. I have used mysql for my application. I want to replace the full stop on the nth position in php.";
for($pos=-1,$i=0; $i<$n; ++$i){
if(($pos=strpos($string,'.',$pos+1))===false){ // locate and store offset
break; // no qualifying dot to remove
}
}
echo $pos===false?$string:substr($string,0,$pos),substr($string,$pos+1); // qualifying portions of $string
Output:
My name is Resheil. I'm developing in PHP. I have used mysql for my application. I want to replace the full stop on the nth position in php