📜  正则表达式g来识别句子中的圣经引用 - Javascript代码示例

📅  最后修改于: 2022-03-11 15:03:00.288000             🧑  作者: Mango

代码示例1
addLinks($text);

class ScriptureUtils {

    private $booksAbbreviated = array(
        "Gen", "Exo", "Lev", "Num", "Deu", "Jos", "Jud", "Rut", "1 Sam", "2 Sam", "1 Kin", 
        "2 Kin", "1 Chr", "2 Chr", "Ezr", "Neh", "Est", "Job", "Psa", "Pro", "Ecc", "Son", 
        "Isa", "Jer", "Lam", "Eze", "Dan", "Hos", "Joe", "Amo", "Oba", "Jon", "Mic", 
        "Nah", "Hab", "Zep", "Hag", "Zec", "Mal", "Mat", "Mar", "Luk", "Joh", "Act", 
        "Rom", "1 Cor", "2 Cor", "Gal", "Eph", "Phi", "Col", "1 The", "2 The", "1 Tim", 
        "2 Tim", "Tit", "Phi", "Heb", "Jam", "1 Pet", "2 Pet", "1 Joh", "2 Joh", "3 Joh", 
        "Jud", "Rev"
    );

    private $booksFullnames = array(
        "Genesis", "Exodus", "Leviticus", "Numbers", "Deuteronomy", "Joshua", "Judges", 
        "Ruth", "1 Samuel", "2 Samuel", "1 Kings", "2 Kings", "1 Chronicles", 
        "2 Chronicles", "Ezra", "Nehemiah", "Esther", "Job", "Psalms", "Proverbs", 
        "Ecclesiastes", "Song of Solomon", "Isaiah", "Jeremiah", "Lamentations", "Ezekiel", 
        "Daniel", "Hosea", "Joel", "Amos", "Obadiah", "Jonah", "Micah", "Nahum", 
        "Habakkuk", "Zephaniah", "Haggai", "Zechariah", "Malachi", "Matthew", "Mark", 
        "Luke", "John", "Acts", "Romans", "1 Corinthians", "2 Corinthians", "Galatians", 
        "Ephesians", "Philippians", "Colossians", "1 Thessalonians", "2 Thessalonians", 
        "1 Timothy", "2 Timothy", "Titus", "Philemon", "Hebrews", "James", "1 Peter", 
        "2 Peter", "1 John", "2 John", "3 John", "Jude", "Revelation"
    );

    private $addLinkPattern;

    public function __construct() {
        $this->defineLinkPattern();
    }

    public function addLinks($text) {
        $returnString = preg_replace_callback(
            $this->addLinkPattern,
            array($this, "addLinkCallback"),
            $text
        );
        return $returnString;
    }

    private function addLinkCallback($matches) {
        $returnString = "";
        foreach($matches as $match) {
            $returnString .= "$match";
        }
        return $returnString;
    }

    private function defineLinkPattern() {
        // It is important that the full names appear before the abbreviated ones.
        $bookList = implode("|", array_merge($this->booksFullnames, $this->booksAbbreviated));
        $this->addLinkPattern = "/\\b(?:$bookList)(?:\\s+\\d+)?(?::\\d+(?:–\\d+)?(?:,\\s*\\d+(?:–\\d+)?)*)?/";
    }

}