15/01/2016 - PHP
As the title describes, this example replaces the beginning of a string with preg_replace
if it starts with a specific string.
You want to turn /api/admin/123/456/api/admin/api/ipa/0
into /api/ipa/123/456/api/admin/api/ipa/0
.
$string = '/api/admin/123/456/api/admin/api/ipa/0';
$prefix = '/api/admin/';
$replace = '/api/ipa/';
echo preg_replace('@^'.$prefix.'@', $replace, $string);
# Result
/api/ipa/123/456/api/admin/api/ipa/0
As you can see $prefix
can be an array so no need to loop through if there are multiple conditions.
$string1 = '/api/admin/123/456/api/admin/api/ipa/0';
$string2 = '/api/user/123/456/api/user/api/ipa/0';
$prefix = ['@^/api/admin/@', '@^/api/user/@'];
$replace = '/api/ipa/';
echo preg_replace($prefix, $replace, $string1);
echo PHP_EOL;
echo preg_replace($prefix, $replace, $string2);
# Result
/api/ipa/123/456/api/admin/api/ipa/0
/api/ipa/123/456/api/user/api/ipa/0