Question

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_replace to avoid regex complications.

Was it helpful?

Solution

Your examples are working fine for me.

But it looks like you are calling the function holding this code twice, so you replace the in to main, and then (by accident) again the in in main to mamain.

Can you ensure that this code is only executed once on your variable?

OTHER TIPS

You can use preg_replace here:

$canonical = 'http://eg.com/uk/sample-post/';
echo preg_replace('/\buk\b/', 'main', $canonical) . "\n";

$canonical = 'http://eg.com/main/sample-post/';
echo preg_replace('/\bmain\b/', 'uk', $canonical) . "\n";

OUTPUT:

http://eg.com/main/sample-post/
http://eg.com/uk/sample-post/

It seems to work for me:

$string = 'http://eg.com/uk/sample-post/';

echo substr_replace( $string, 'main', strpos($string,'uk'), strlen('uk'));

You could also use:

$string = 'http://eg.com/uk/sample-post/';

echo str_replace('uk','main', $string);

But this will replace all occurrences...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top