How to insert character in a string at specific position with PHP

2 Answers

0 votes
function insert_char(&$s, $pos, $ch) { 
    $s = substr($s, 0, $pos) . $ch . substr($s, $pos);
} 



$s = "PHPPythonJavaC#C++"; 

insert_char($s, 3, " ");
insert_char($s, 13, "W");
        
echo $s;



    
/*
run:

PHP PythonJavWaC#C++
         
*/

 



answered Jan 16, 2020 by avibootz
0 votes
$s = "PHPPythonJavaC#C++"; 
 
$s = substr_replace($s, " ", 3, 0);
echo $s . "\n";

$s = substr_replace($s, "W", 11, 0);

echo $s;
 
 
 
     
/*
run:
 
PHP PythonJavaC#C++
PHP PythonJWavaC#C++
          
*/

 



answered Oct 14, 2020 by avibootz

Related questions

3 answers 186 views
2 answers 248 views
1 answer 203 views
1 answer 176 views
2 answers 254 views
...