【问题标题】:php function to return words instead of characters not workingphp函数返回单词而不是字符不起作用
【发布时间】:2014-02-04 14:55:08
【问题描述】:

我正在使用 php 函数返回单词而不是字符,当我将字符串传递给函数时它工作正常,但我有一个变量等于另一个包含字符串的变量,我尝试了主变量但没有工作

////////////////////////////////////////////////////////
function words($text)
{
$words_in_text = str_word_count($text,1);
$words_to_return = 2;
$result = array_slice($words_in_text,0,$words_to_return);
return '<em>'.implode(" ",$result).'</em>';
}

$intro = $blockRow03['News_Intro'];

echo words($intro); 

/* echo words($blockRow03['News_Intro']);  didn't work either */

结果什么都没有

【问题讨论】:

  • 你的功能看起来不错。 echo $blockRow03['News_Intro']; 工作吗?因为如果你传递字符串并且它可以工作,那么问题很可能在于变量。
  • 是的,它可以工作并回显文本
  • 我认为问题出在其他语言上,它适用于英语

标签: php substr


【解决方案1】:

str_word_count 不适用于重音(多字节)字符。你可以使用下面的sanitize words 函数来解决这个问题:

function sanitize_words($string) {
    preg_match_all("/\p{L}[\p{L}\p{Mn}\p{Pd}'\x{2019}]*/u",$string,$matches,PREG_PATTERN_ORDER);
    return $matches[0];
}
function words($text)
{
$words_in_text = sanitize_words($text);
$words_to_return = 2;
$result = array_slice($words_in_text,0,$words_to_return);
return '<em>'.implode(" ",$result).'</em>';
}

$intro = "aşağı yukarı böyle birşey";

echo words($intro); 

【讨论】:

  • 你好。上面的函数效果很好,但它消除了引号。如果我有这样的短语: some "text" here 它会在此处返回一些文本。有什么帮助吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-04
  • 2013-05-16
  • 1970-01-01
  • 2017-08-08
相关资源
最近更新 更多