This is my simple code:
$string = "PAAUSTRALIA" ;
$output = str_replace("A","",$string);
$output = str_replace("P","",$output);
Here output is: USTRLI
But, my desired output is AUSTRALIA.
Is there any easy way in php to do this task? Simply, I want to replace one character each time from the left side of the string for my project.
The Java string replace() method will replace a character or substring with another character or string. The syntax for the replace() method is string_name. replace(old_string, new_string) with old_string being the substring you'd like to replace and new_string being the substring that will take its place.
replace() method helps to replace the occurrence of the given old character with the new character or substring. The method contains the parameters like old(a character that you wish to replace), new(a new character you would like to replace with), and count(a number of times you want to replace the character).
In Python, the . replace() method and the re. sub() function are often used to clean up text by removing strings or substrings or replacing them.
You have to use a function to do this task smoothly. Please have a look at my code:
<?php
function onereplace($str,$replaced_character){
$spt = str_split($str,1);
for($i=0; $i <= (count($spt) - 1) ; $i++){
if($spt[$i] == $replaced_character){
unset($spt[$i]);
break;
}
}
return implode('',$spt);
}
$string = "PAAUSTRALIA" ;
$string = onereplace($string,"P");
echo $string = onereplace($string,"A");
?>
Hope it will help you!!!
Try substr along with strpos instead of str_replace as
$string = "PAAUSTRALIA" ;
$string = substr($string,(strpos($string, 'P') > -1));
$string = substr($string,(strpos($string, 'A') > -1));
echo $string; //AUSTRALIA
Edited
Making a function will also do the same as
echo removeOne($string,'p');
function removeOne($str,$value){
return substr($str,(stripos($str,$value) > -1));
}
str_replace will find the occurrence of letter 'A' within string and replace it to ''
Another Option would be to use preg_replace
which supports a limit-parameter:
http://php.net/manual/en/function.preg-replace.php
$string = "PAAUSTRALIA" ;
$string = preg_replace("@A@", "", $string, 1);
$string = preg_replace("@P@", "", $string, 1);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With