As I was playing with the WordPress shortcode methods, I came upon an interesting problem.
I wanted to change text in the particular line of the shortcode content and thus standard PHP explode and implode methods seemed like a best bet:
add_shortcode('something', 'something_callback');
function snippet_pre_shortcode_callback($atts, $content = null) {
$lines = explode('\n', $content);
$lines[1] = "My line 2";
return implode('\n', $lines);
}
Nice and simple solution that didn't work. The big content string I was sure had some lines, wouldn't split. It took me a while to notice the error - single quote in PHP does not specify character but string with a minimal escaping. Most of the time they behave same as the double quotes which actually allow for much richer escaping.
Most annoying was that I knew this "feature" from before. However, too much work in the proper programming languages kinda made me overlook this trivial error multiple times while debugging. After taking a "frustration break" and coming back after 5 minutes, mistake was obvious.
The easy solution would be to swap one quotes for another. However, in this case a bit nicer solution exists - use the damn PHP_EOL constant:
function snippet_pre_shortcode_callback($atts, $content = null) {
$lines = explode(PHP_EOL, $content);
$lines[1] = "My line 2";
return implode(PHP_EOL, $lines);
}
PHP, who wouldn't love you... :/