-4

我有一些大字符串,以及一些必须用一些更改替换的单词数组,比如包装在链接中。第一个问题是包装整个单词或组合单词。第二个问题是每 1000 个字符至少执行上一步。

$string="lalala word lalala blah, blah lalala combination of words lalala lalala...";  
$patterns=array('word','combination of words');  
$replacements=array('<a href="#">word</a>','<a href="#">combination of words</a>');  

例如,我之前必须对片段做什么?

4

2 回答 2

0

在我看来,您正在寻找wordwrap(). 然后,您可以preg_replace_callback()将其应用于您的搜索模式并进行替换:

foreach ($patterns as $pattern) {
    $regex = '/' . preg_quote($pattern, '/') . '/';
    $string = preg_replace_callback($regex, function($match) {
        return '<a href="#">'
            . wordwrap(htmlspecialchars($match), 1000, '<br />')
            . '</a>';
    }, $string);
}
于 2012-07-15T20:23:52.710 回答
0

解决方案:

 <?php
        function set_keys_by_words($content, $key, $words,$before,$after) {
        $positions = array();
        $string = '';
        for ($i = 0; $i < count($words); $i++) {

            $string = preg_replace('/\b' . $words[$i] . '\b/ui', $key . $words[$i], $content);
            $position = mb_strpos($string, $key);

            if ($position != '') {
                $positions[(int) $position] = $words[$i];
            }
        }
        ksort($positions);
        $word = '';
        $number = '';
        $i = 0;
        foreach ($positions as $k => $v) {
            $i++;
            if ($i == 1) {
                $number = $k;
                $word = $v;
            }
        }
        if ((int) $number) {
            $word_len = strlen($word);
            $part_after = preg_replace('/\b' . $word . '\b/ui', $before . $word . $after, mb_substr($content, 0, $number + $word_len));
            echo $part_after . mb_substr($content, $number + $word_len, 1000);
            $content = mb_substr($content, $number + $word_len + 1000);
            if ($content != '') {
                set_keys_by_words($content, $key, $words);
            }
        } else if ($number == '' && $content != '') {
            echo $content;
        }
    }
    ?>
于 2012-07-16T09:40:25.247 回答