Example: (UPDATED - corrected the code below)
<?php
$canonical = 'http://eg.com/in/sample-post/';
$pos = strpos( $canonical, 'in' );
echo substr_replace( $canonical, 'main', $pos, strlen('in') );
// OUTPUT: http://eg.com/mamain/sample-post/
?>
As shown in the example, I am trying to replace the first instance of uk (subject) in the URL with main (replacement). Instead the output shows mamain. I am not sure why.
But the same code seems to work if the no. of characters in the subject is greater than replacement, e.g.
<?php
$canonical = 'http://eg.com/main/sample-post/';
$pos = strpos( $canonical, 'main' );
echo substr_replace( $canonical, 'uk', $pos, strlen('main') );
// OUTPUT: http://eg.com/uk/sample-post/
?>
Clearly, the second code although the same, does what I intend it to do.
How do I modify the code so that it works in both instances? What logic am I missing here?
NOTE:
The code is only to give you an idea of what I am doing.
I'd like to avoid having to use
preg_replaceto avoid regex complications.
http://eg.com/main/sample-post/as intended. Are you sure that there is no other error in your original code?intomain, and then (by accident) again theininmaintomamain. Can you ensure that this code is only executed once on your variable?