1. I'm trying to write a function that will do a find-and-replace on the entry text. It would search the entry for foo and replace every instance of foo with bar. Is this even possible
( Read more... )
You can do a search and replace, but you can't use regexes or wildcards. (Although I think I saw someone making an attempt at that too, so maybe it is possible. I just don't remember where the entry was, most likely s2styles.)
Anyway, I use a function created by mageboltrat:
function replace_text(string text, string find, string replacement) : string "Search within \$text and replaces any occurences of \$find with \$replacement." {
#######################################################
# from lj:mageboltrat's industrial nippon (id=533012) #
#######################################################
var string[] findarray;
var int pos = 1;
foreach var string findcharacter($find) {
$findarray[$pos] = $findcharacter;
$pos = $pos + 1;
}
var int place = 1;
var bool found = false;
var string completedtext = "";
var string foundtext = "";
foreach var string searchcharacter($text) {
if ($searchcharacter == $findarray[$place]) {
if ($place == $find->length()) {
$foundtext = $replacement;
$place = 1;
} else {
$foundtext = $foundtext + $searchcharacter;
$place = $place + 1;
}
} else {
$completedtext = $completedtext + $foundtext + $searchcharacter;
$foundtext = "";
$place = 1;
}
}
$completedtext = $completedtext + $foundtext;
return $completedtext;
}
And another function to actually put in your search and replace criteria:
function alter_entry(string original) : string {
var string[] find;
var string[] replace;
$find[0] = "";
$replace[0] = "123";
$find[1] = "";
$replace[1] = "789";
foreach var int i (0 .. (size($find) - 1)) {
$original = replace_text($original, $find[$i], $replace[$i]);
}
return $original;
}
And then you should use it something like this:
if ($e.text_must_print_trusted) {
$e->print_text();
} else {
print alter_entry($e.text);
}
It's very important to use the $e.text_must_print_trusted logic, because otherwise the VoicePosts and embedded videos will break your journal.
Reply
Reply
Leave a comment