【问题标题】:PHP transform a text to meta keywordsPHP 将文本转换为元关键字
【发布时间】:2013-05-12 14:01:49
【问题描述】:

我想转换给定的文本,如

“Lorem ipsum dolor sit amet, consectetur adipiscing elit! Nam suscipit | Actor pellentesque。”

到页面中的元关键字。为此,我需要排列文本并过滤除文本之外的所有内容(无标点符号)。

全部小写,包含 3 个或更少字符的单词应省略。最终输出应如下所示:

“lorem, ipsum, dolor, amet, consectetur, adipiscing, elit, suscipit, 拍卖师, pellentesque"

我到处寻找解决方案,但由于我是 php 新手,所以对我来说几乎就像中文。

【问题讨论】:

  • 那你自己试过什么? str_word_count() 可能是一个有用的起点,使用 array_walk() 转换为小写,array_filter() 删除所有长度不超过 3 个字符的单词

标签: php string text replace


【解决方案1】:

希望这会有所帮助!

// Set the phrase into an array
$keywords = "Lorem ipsum dolor sit amet, consectetur adipiscing elit! Nam suscipit | Auctor pellentesque"; 

// Remove all special characters to only leave alphanumeric characters (and whitespace)
$keywords = preg_replace('/[^A-Za-z0-9\s]/', '', $keywords);

// Explode the phrase into an array, splitting by whitespace
$keywords = explode(' ', $keywords);


// Create an empty array to store keywords
$end = array();

// Loop through each keyword
foreach($keywords as $keyword){

   // Check that the keyword is greater than 3 characters long
   // If it is, add it to the $end array
   if(strlen($keyword)>3){ $end[] = strtolower($keyword); }
}

// Implode the $end array into a comma seperated list
echo implode(', ', $end);

编辑:从导致错误的代码中删除了一个额外的括号

【讨论】:

  • 你错过了implode()中的参数顺序。
  • 非常感谢.. 成功了。对不起,如果我的问题听起来很愚蠢,但我确实从你们在这里写的东西中学到了很多..
【解决方案2】:
function getMetaString($string) {
    preg_match_all("/[a-z0-9\-]{4,}/i", $string, $output_array);

    if(is_array($output_array) && count($output_array[0])) {
        return strtolower(implode(',', $output_array[0]));
    } else {
        return '';
    }
}

$string = "Lorem ipsum dolor sit amet, consectetur adipiscing elit! Nam suscipit | Auctor pellentesque.";

echo getMetaString($string); // Output: lorem,ipsum,dolor,amet,consectetur,adipiscing,elit,suscipit,auctor,pellentesque

用到的功能: implode, preg_match_all

【讨论】:

    【解决方案3】:

    试试这个:

    $text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit! Nam suscipit | Auctor pellentesque.";
            preg_match_all('/\w{4,}/i', $text, $matches);
            $meta = join(',', $matches[0]);
            print_r('<pre>');
            print_r($meta);die();
    

    【讨论】:

      【解决方案4】:
      $string = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit! Nam suscipit | Auctor pellentesque.';
      $string = strtolower($string);
      $meta   = array();
      $words  = preg_split('/[^a-z]+/', $string);
      foreach ($words as $word) {
          if (strlen($word) > 3) {
             $meta[] = $word;
          }
      }
      
      echo implode(', ', $meta);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-06-10
        • 2022-08-18
        • 2015-08-23
        • 2013-07-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多