douluolan9101 2018-03-28 12:30
浏览 39
已采纳

数组:使用preg_replace和排序过滤[PHP - WordPress]

I have a list of categories that are made up of multiple recurring (italian) words, like this:

  • racconti sulla vita
  • racconti di passione
  • racconti sui pensieri
  • racconti motivazionali
  • ...

What I need to do is remove from the list all the recurring words (racconti, sulla, di, sui, sul, etc.) and then order the rest from A to Z.

The result is really weird: the total number of categories is 42 and I get the first 31 results in the right order (in this case from B to V). From 32nd item, the list starts again in the right order (from A to S).

It's like if the list was split in 2 parts.

This is my code:

$terms_tipologia = get_terms( 'tipologia', array( 'hide_empty' => true ) );

foreach ( $terms_tipologia as $tipologia ) :

    $words = array("racconti", "sul", "sull'", "sulla", "sulle", "sullo", "sui", "di");
    $pattern = '/\b(?:' . join('|', $words) . ')\b/i';

    $term_name = preg_replace($pattern, '', $tipologia->name);
    $term_link = get_term_link($tipologia);

    $reorder[$term_link] = $term_name;

endforeach;

asort($reorder);

foreach ( $reorder as $link => $nome ) :

    echo '<li><a href="'.esc_url( $link ).'">' . $nome . '</a></li>';

endforeach;
  • 写回答

1条回答 默认 最新

  • doutusheng5879 2018-03-28 12:49
    关注

    i think your issue come from space before/after removed word.

    here sample than should work :

    $terms_tipologia = [
        'racconti sulla vita',
        'racconti di passione',
        'sulle amotivazionali',
         'boem sulle ',
        'racconti sui pensieri',
        'racconti motivazionali'
    ];
    
    $words = ["racconti", "sul", "sull'", "sulla", "sulle", "sullo", "sui", "di"];
    //You should not rebuild on each loop iteration your pattern, i have also add optional space on regex.
    $pattern = '/\b\s*(?:' . join('|', $words) . ')\s*\b/i';
    $reorder = [];
    foreach ( $terms_tipologia as $tipologia ) {
    
        $term_name = preg_replace($pattern, '', $tipologia);
        $reorder[] = trim($term_name); // I remove useless space.
    }
    
    asort($reorder);
    
    var_dump($reorder);
    

    You can see online example : http://sandbox.onlinephpfunctions.com/code/21a4c4beb156e2a4904f4a913a9b60334496d2d7

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里