How can I in php, append a character to another character within! a string, with perhaps regex.
If I have an array, lets say:
$array=["a","b","c","d","e","f","g","h","i","j"];
$long_string="yada yada yada yada yada....";
If I wanted to append an exclamation mark to each of the characters in $array, found in $long_string how would that be done with regex? At the moment my skills only give me the option to do a loop over the string, and I understand that is not the smoothest way to do it.
Grateful for any help!
Wiktor Stribiżew :
You may use str_replace that may take an array of search and replace values. The replacement value array can be easily built from the search char array using array_map.\n\nSee PHP demo:\n\n$array=[\"a\",\"b\",\"c\",\"d\",\"e\",\"f\",\"g\",\"h\",\"i\",\"j\"];\n$repl = array_map(function ($i) { return $i.\"!\"; }, $array);\n$long_string=\"yada yada yada yada yada....\";\necho str_replace($array, $repl, $long_string);\n// => ya!d!a! ya!d!a! ya!d!a! ya!d!a! ya!d!a!....\n\n\nA regex approach (if the search items are single alpha characters):\n\n$array=[\"a\",\"b\",\"c\",\"d\",\"e\",\"f\",\"g\",\"h\",\"i\",\"j\"];\n$long_string=\"yada yada yada yada yada....\";\n$rx = \"[\" . implode(\"\", $array) . \"]\";\necho preg_replace('/'.$rx.'/', '$0!', $long_string);\n\n\nSee the PHP demo. The regex will be /[abcdefghij]/ (a character class that matches a single char) and the replacement contains the backreference to the whole match ($0) and the ! symbol added to each match.\n\nIf your search items are multiple char strings and can contain non-word chars, it is safer to use an alternation group and preg_quote the items (demo):\n\n$rx = \"(?:\" . implode(\"|\", array_map(function($i) {return preg_quote($i, \"/\");}, $array)) . \")\";\necho preg_replace('/'.$rx.'/', '$0!', $long_string);\n\n\nThe regex will look like (?:a|b|c|d|e|f|g|h|i|j) then. \n\nAll regexps can be tested at regex101.com.",
2016-11-09T13:21:07