I have a String as follows:
$var = "Hello Hi World it is an awesome day. Test Hi guys Whats up";
I am trying to replace the value in my string as follows:
function get_string_between($string, $start, $end){
$string = " ".$string;
$ini = strpos($string,$start);
if ($ini == 0) return "";
$ini += strlen($start);
$len = strpos($string,$end,$ini) - $ini;
return substr($string,$ini,$len);
}
$parsed0 = get_string_between($var, "Hello", "World");
So I get the String in `$parse0`
And I am replacing as follows:
$varnew = str_replace($parsed0,"NEWVALUE", $var);
echo $varnew;
I get output as follows:
Hello NEWVALUE World it is an awesome day. Test NEWVALUE guys Whats up
My expected result is:
Hello NEWVALUE World it is an awesome day. Test Hi guys Whats up.
This is happening because in $parse0
I get result as Hi
and it contains two times in that String.
Is there any way I get start and and end positions using a function and replace it using those?
I would suggest preg_replace_callback. Check the code below.
function customReplace($string, $start, $end, $value = "NEWVALUE"){
return preg_replace_callback('/'.$start.'(.*?)'.$end.'/', function($m) use($start, $end){
return "$start NEWVALUE $end";
}, $string);
}
$var = "Hello Hi World it is an awesome day. Test Hi guys Whats up";
echo customReplace($var, "Hello", "World");
Output:
Hello NEWVALUE World it is an awesome day. Test Hi guys Whats up
Problem with your code is:
$varnew = str_replace($parsed0,"NEWVALUE", $var);
$parsed0
has Hi
(which you fetched from the function), and saying str_replace
to replace Hi
with NEWVALUE
in the string $var
(whole string). So str_replace
is working as expected. Hope it is clear now.
UPDATE
Also check @b263 answer below. You can use preg_replace too, it doesn't require a callback.
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加