Just wondering if it is possible to change a character in a string with more than 1 character. Here’s my failed attempt:
<?
$string = abcde;
echo "character 2: ". $string[2] . "\n";
$string[2] = "X";
echo "character 2: ". $string[2] . "\n";
$string[2] = "moreThanOneChar";
echo "character 2: ". $string[2] . "\n";
echo "whole string: $string";
?>
output:
character 2: c
character 2: X
character 2: m
whole string: abmde // <-- This should be abmoreThanOneCharde
You can solve this using a regular expression (regex) replacement mechanism:
Note; however, that this will replace every instance of ‘X’ with ‘moreThanOneChar’. If you want to limit this to only the first time, you can pass a limit as a fourth parameter:
This can be easily expanded to replace phrases:
Output:
Review the
preg_replacecommand for more information:http://php.net/manual/en/function.preg-replace.php