【问题标题】:RegExp trouble with a LONG pattern长模式的正则表达式问题
【发布时间】:2013-12-01 15:58:37
【问题描述】:

在执行正则表达式代码时,通常字符串很长而模式很短,但这次是相反的。我有大约 500 个字符的短文本。在该文本中,我想找到与大约 47.000 个唯一名称的数据库匹配的名称,并添加指向特定名称的链接。这样做的最佳方法是什么?我将名称数组划分为 64 个分区,因为一个数组太大而无法作为模式处理。

function implode_r ($glue, $pieces){
    $out = "";
    foreach ($pieces as $piece){
        if (is_array ($piece)){
            $out .= implode_r ($glue, $piece); // recurse
        }
        else{
            if(strlen($piece)>1){
                $piece = str_replace("(", "\(", $piece);
                $piece = str_replace(")", "\)", $piece);
                $piece = str_replace("[", "\[", $piece);
                $piece = str_replace("]", "\]", $piece);
                $piece = str_replace(":", "\:", $piece);
                $piece = str_replace(".", "\.", $piece);
                $piece = str_replace(",", "\,", $piece);
                $piece = str_replace("'", "\'", $piece);
                $piece = str_replace("&", "\&", $piece);
                $piece = str_replace("?", "\?", $piece);
                $piece = str_replace("!", "\!", $piece);
                $piece = str_replace("<", "\<", $piece);
                $piece = str_replace(">", "\>", $piece);
                $piece = str_replace("{", "\{", $piece);
                $piece = str_replace("}", "\}", $piece);
                $out .= $glue.$piece;
            }
        }
    }
    return $out;
}

function partition( $list, $p ) {
    $listlen = count( $list );
    $partlen = floor( $listlen / $p );
    $partrem = $listlen % $p;
    $partition = array();
    $mark = 0;
    for ($px = 0; $px < $p; $px++) {
        $incr = ($px < $partrem) ? $partlen + 1 : $partlen;
        $partition[$px] = array_slice( $list, $mark, $incr );
        $mark += $incr;
    }
    return $partition;
}

add_filter( 'the_content', 'find_names_in_text');
add_filter( 'get_the_content', 'find_names_in_text');
function find_names_in_text($content){
    global $wpdb;
    $thenames = $wpdb->get_results("SELECT post_title FROM $wpdb->posts WHERE post_type='dogs' GROUP BY post_title", ARRAY_N);
    $namesparts = partition($thenames, 64);
    foreach($namesparts as $part){
        $pattern = implode_r("|", $part);
        $content = preg_replace("(".$pattern.")", "<a href='$1'>$1</a>", $content);
    }
    return $content;
}

【问题讨论】:

  • 旁注,您可以在str_replace() 中使用数组,例如str_replace(array('a', 'b'), array('c', 'd'), $input);

标签: php regex wordpress replace preg-replace


【解决方案1】:

如果您的文本只有 500 个字符,我会反其道而行之。将文本分成可能是名称的部分(假设这些是单词,我认为没有拆分单词的名称)。

所以现在您的数据库中有

【讨论】:

  • 谢谢!现在的问题是将文本拆分为可能的名称,因为所有名称中都包含一个以上的单词。这是我需要摆脱代码的示例,但只有模式中的匹配名称。 regexr.com?3787i
  • 嗯,这很可惜,但并非不可能:使用滑动/移动窗口算法之类的东西,理论上您应该能够将字符集拆分为多个不同的单词组,并根据数据库。您会收到更多查询,但如果有 500 个字符,这可能不会太多?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-16
  • 1970-01-01
  • 2015-07-11
  • 2019-01-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多