javascript - 摘抄();函数不计算/处理日语单词

标签 javascript php jquery wordpress plugins

我正在开发日语网站,并使用此代码进行字数限制,当我粘贴英语句子但不使用日语单词时,它可以工作。

function content($num) {
$theContent = get_the_content();
$output = preg_replace('/<img[^>]+./','', $theContent);
$output = preg_replace( '/<blockquote>.*<\/blockquote>/', '', $output );
$output = preg_replace( '|\[(.+?)\](.+?\[/\\1\])?|s', '', $output );
$limit = $num+1;
$content = explode(' ', $output, $limit);
array_pop($content);
$content = implode(" ",$content)."...";
  echo $content;
}


<?php content('15'); ?>

任何人都可以帮助我,一件事是我正在使用 xeory_extension 主题。

最佳答案

问题是日语字符是多字节的(平假名和片假名字符在 UTF-8 中存储在 3 个字节上),因此您必须使用 special php multibytes string functions操作包含日语字符的字符串。

遗憾的是 PHP 没有提供开箱即用的 mb_explode 函数。尽管有些人对此进行了研究,使用 mb_strlenmb_substr 来构建缺失的函数。

以下代码是我的注释,它来自 the fetus-hina mb_explode gist :

function mb_explode($delimiter, $string, $limit = -1, $encoding = 'auto') {
    if(!is_array($delimiter)) {
        $delimiter = array($delimiter);
    }
    if(strtolower($encoding) === 'auto') {
        $encoding = mb_internal_encoding();
    }
    if(is_array($string) || $string instanceof Traversable) {
        $result = array();
        foreach($string as $key => $val) {
            $result[$key] = mb_explode($delimiter, $val, $limit, $encoding);
        }
        return $result;
    }

    $result = array();
    $currentpos = 0;
    $string_length = mb_strlen($string, $encoding);
    while($limit < 0 || count($result) < $limit) {
        $minpos = $string_length;
        $delim_index = null;
        foreach($delimiter as $index => $delim) {
            if(($findpos = mb_strpos($string, $delim, $currentpos, $encoding)) !== false) {
                if($findpos < $minpos) {
                    $minpos = $findpos;
                    $delim_index = $index;
                }
            }
        }
        $result[] = mb_substr($string, $currentpos, $minpos - $currentpos, $encoding);
        if($delim_index === null) {
            break;
        }
        $currentpos = $minpos + mb_strlen($delimiter[$delim_index], $encoding);
    }
    return $result;
}

然后就像使用爆炸一样使用它:

$content = mb_explode(' ', $output, $limit);

对于内爆you shouldn't have any issue .

关于javascript - 摘抄();函数不计算/处理日语单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33252656/

相关文章:

javascript - 如何在文本框为空时返回焦点

php - 从数组中的每个字符串中提取一个或多个符合条件的子字符串

javascript - 鼠标单击对象数组javascript Canvas

javascript - 浏览器后退和前进按钮不使用 history.js 的 statechange 事件调用回调方法

javascript - 播放 mp3 时突出显示文本

php - 在 PHP 中连接文件

javascript - 从表单在同一页面内调用 JS 函数(AJAX)

javascript - 如何在javascript中创建一个高于其他标签的html标签?

javascript - 为什么我不能对从 jquery $.makeArray() 创建的数组对象使用 java 脚本方法 Sort()

javascript - 参数列表后缺少 )。 (第 6 行文件 "code")