Reputation: 955
I have a lot of text in my editor with references in brackets. So for example.
"This is text, welcome to my text [11]. We have several sources [23]. What can I do for you [33]"
I want to find each number in between the brackets and replace that number with an anchor tag containing it, like so <xref ref-type="bibr" rid="R11">[11]</xref>
and then <xref ref-type="bibr" rid="R23">[23]</xref>
What I am doing now is finding the numbers in brackets with a regex ( \[.*?] ) in the editor and then copy and pasting what I want to replace. This is time consuming when there are over 100 references to replace.
Is there a way to find, store it in a variable and then replace with said variable?
One possible solution I came up with is using JavaScript, however I cannot get it to work quite right, as evident by my output.
Code:
const document = 'This is text, welcome to my text [11]. We have several sources [23]. What can I do for you [33]'
const regex = /\[.*?\]/gm
let result = document.match(regex);
let array = result
var arrayLength = array.length;
console.log(arrayLength);
for (var i = 0; i < arrayLength; i++) {
console.log(document.replace(regex, '<xref ref-type="bibr" rid="R' + array[i] + '">' + array[i] + "</xref>"));
}
Console Output:
This is text, welcome to my text <xref ref-type="bibr" rid="R[11]">[11]</xref>. We have several sources <xref ref-type="bibr" rid="R[11]">[11]</xref>. What can I do for you <xref ref-type="bibr" rid="R[11]">[11]</xref>
This is text, welcome to my text <xref ref-type="bibr" rid="R[23]">[23]</xref>. We have several sources <xref ref-type="bibr" rid="R[23]">[23]</xref>. What can I do for you <xref ref-type="bibr" rid="R[23]">[23]</xref>
This is text, welcome to my text <xref ref-type="bibr" rid="R[33]">[33]</xref>. We have several sources <xref ref-type="bibr" rid="R[33]">[33]</xref>. What can I do for you <xref ref-type="bibr" rid="R[33]">[33]</xref>
As you can see, I also need to remove the brackets from the rid= attribute. I also would like to get this done in the editor itself. If it is not possible, then I figured I can use node.js and write to the file. Any other solution would also help. Should this be done in Python?
Upvotes: 0
Views: 54
Reputation: 1934
This PHP code gets it done:
<?php
$str = 'This is text, welcome to my text [11]. We have several sources [23]. What can I do for you [33]';
function addLink ($matches){
$noBrackets = str_replace('[', '', $matches[0]);
$noBrackets = str_replace(']', '', $noBrackets);
$output = '<xref ref-type="bibr" rid="R'.$noBrackets.'">'.$matches[0].'</xref>';
return $output;
}
$newString = preg_replace_callback('#\[\d+\]#', 'addLink', $str);
echo '<p>'.$newString.'</p>';
?>
Upvotes: 1