How to replace one left character with a string?

This is my simple code:

$string = "PAAUSTRALIA" ; $output = str_replace("A","",$string); $output = str_replace("P","",$output); 

Here's the output: USTRLI

But my desired result is AUSTRALIA.

Is there an easy way in php to accomplish this task? I just want to replace every time one character on the left side of the string for my project.

+6
source share
7 answers

You must use the function to complete this task seamlessly. Check out 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 this helps you.

+3
source

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 by

Executing a function will also do the same thing as

 echo removeOne($string,'p'); function removeOne($str,$value){ return substr($str,(stripos($str,$value) > -1)); } 

str_replace will find the letter "A" inside the string and replace it with ''

+2
source

Another option is to use preg_replace , which supports the 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); 
+1
source

Please use this function in php for your task: substr(yourstring, startindex, endindex)

<b> Edited

substr(yourstring, 0, strlen($yourstring))
For reference, refer to the link: http://php.net/substr

Hope this helps you.

0
source
 echo substr($string ,1,strlen($string)); 

Link:

 substr(string,start,length) 
0
source

str_replace will replace all characters matched in a string.

Try using substr ()

 $string = "AAUSTRALIA" ; $output = substr($string, 1); 
0
source

If you just want to remove 1 char at the left time, then you only need substr ():

 $string = "PAAUSTRALIA" ; $string = substr($string, 1); // AAUSTRALIA $string = substr($string, 1); // AUSTRALIA 
0
source

Source: https://habr.com/ru/post/987336/


All Articles