Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace one left character from a string?

Tags:

php

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.

like image 518
Asif Iqbal Avatar asked May 16 '15 13:05

Asif Iqbal


People also ask

How do you replace a specific character in a string?

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.

How do you replace a single character in a string in Python?

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).

How do you replace part of a string in Python?

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.


3 Answers

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!!!

like image 176
Asif Iqbal Avatar answered Oct 21 '22 01:10

Asif Iqbal


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 ''

like image 29
Narendrasingh Sisodia Avatar answered Oct 21 '22 01:10

Narendrasingh Sisodia


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);
like image 1
dognose Avatar answered Oct 21 '22 00:10

dognose