我正在日语网站上工作,并使用此代码进行单词限制,当我粘贴英语句子但不使用日语单词时,它正在工作。
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
主题。
答案 0 :(得分:0)
问题是日文字符是多字节的(平假名和片假名字符存储在UTF-8中的3个字节上),因此您必须使用special php multibytes string functions来处理包含日文字符的字符串。
遗憾的是,PHP没有提供开箱即用的mb_explode
功能。虽然有些人就是这样做的,但是使用mb_strlen
和mb_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;
}
然后就像使用explode一样使用它:
$content = mb_explode(' ', $output, $limit);
implode
,you shouldn't have any issue。
答案 1 :(得分:0)
这对我有用
function custom_short_excerpt($excerpt){
$limit = 200;
if (strlen($excerpt) > $limit) {
return substr($excerpt, 0, strpos($excerpt, ' ', $limit));
}
return $excerpt;
}
add_filter('the_excerpt', 'custom_short_excerpt');