Home > Back-end >  How to prevent str_replace() to replace strings twice?
How to prevent str_replace() to replace strings twice?

Time:02-24

I want to replace specific url parts with PHP on website init. So the str_replace is called on each website request.

Lets say this is my string:/wp-content/plugins/app/creator/

I want to replace

/wp-content/plugins/app/

with

https://www.example.com/wp-content/plugins/app/.

To replace this part of the string I'm using the following code:

<?php
str_replace('/wp-content/plugins/app/', 'https://www.example.com/wp-content/plugins/app/', '/wp-content/plugins/app/creator/');
?>

This works for the first time. I get the url I need. But on the second request I get something like:

https://www.example.comhttps://www.example.com/wp-content/plugins/app/creator because the string I search for is still there. How could I fix this, so that the str_replace does not replace these strings twice?

CodePudding user response:

You can use preg_replace instead:

<?php

$str = '/wp-content/plugins/app/creator/';
$pattern = '/^\/wp-content\/plugins\/app\//i';

$x = preg_replace($pattern, 'https://www.example.com/wp-content/plugins/app/', $str);
$x = preg_replace($pattern, 'https://www.example.com/wp-content/plugins/app/', $x);
$x = preg_replace($pattern, 'https://www.example.com/wp-content/plugins/app/', $x);
echo $x;
// https://www.example.com/wp-content/plugins/app/creator/

This way, we make sure that we are only replacing a text that is "starting" with that string.

CodePudding user response:

You want preg_replace that will allow you to use regex to only select phrases at the beginning of the string (^). Most regexes use / for the separator, but using ticks here make it easier to read.

$str = '/wp-content/plugins/app/creator/';
$str =preg_replace("`^/wp-content/plugins/app/`", "https://www.example.com/wp-content/plugins/app/", $str);

CodePudding user response:

You can use preg_replace instead, ^ from the regex meaning that is must begin with

print preg_replace('/^(\/wp-content\/plugins\/app\/)/', 'https://www.example.com/wp-content/plugins/app/', '/wp-content/plugins/app/creator/');
  • Related