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

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

报告相同问题?

悬赏问题

  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元