简体   繁体   English

PHP:如何替换这些字符串(有效)?

[英]PHP: how to replace these strings (efficiently)?

I'm using array_intersect() to remove all class es from my Wordpress menu-items, except the ones listed. 我正在使用array_intersect()从我的Wordpress菜单项中删除所有class es,除了列出的那些。 Then I'm using str_replace to rename the classes. 然后我使用str_replace重命名类。 This works, but it feels sloppy. 这有效,但感觉马虎。 Is there a more efficient way of doing this? 有更有效的方法吗?

function my_nav_menu_css_class( $classes ) {

    $classes = array_intersect( $classes, array(
        'current-menu-ancestor',
        'menu-item-has-children',
        'current-menu-item',
    ));

    $classes = str_replace( 'current-menu-ancestor', 'ancestor', $classes );
    $classes = str_replace( 'menu-item-has-children', 'children', $classes );
    $classes = str_replace( 'current-menu-item', 'item', $classes );

    return $classes;
}

add_filter( 'nav_menu_css_class', 'my_nav_menu_css_class' );

Note: the above classes are all conditional ; 注意:上述类都是有条件的 ; they will only appear if the menu is active or is a dropdown menu. 它们仅在菜单处于活动状态或下拉菜单时出现。 In other words, trying this didn't work: 换句话说,尝试这个不起作用:

$rename_classes = array(
    'ancestor',
    'children',
    'item',
);
return str_replace( $classes, $rename_classes, $classes );

In this case .current-menu-item is supposed to be replaced with .item but is replaced with .ancestor instead (because it came first in the array). 在这种情况下, .current-menu-item 应该.item替换,但是替换为.ancestor (因为它在数组中排在第一位)。 So that's no good. 所以这不好。 Any better solutions? 更好的解决方案?

You should update your CSS to use ".current-menu-item" instead. 您应该更新CSS以使用“.current-menu-item”。

Anything you do in PHP will make the website slightly slower to load, and potentially buggy. 您在PHP中执行的任何操作都会使网站加载速度稍慢,并且可能会出错。

The best code is no code at all, only write the minimum amount you need to solve a given problem. 最好的代码根本就没有代码,只写出解决给定问题所需的最小数量。 Less work for you, less bugs and faster execution for the end user. 减少对您的工作,减少错误并为最终用户执行更快。 That's a win all around. 这是一个全面的胜利。

am i reading this right, you are doing something N times (here 3)? 我正在读这个,你做了N次(这里3)? and the end result is the list of classes that exist in the $classes you pass in? 最终结果是您传入的$类中存在的类列表? if this is the case use a foreach loop. 如果是这种情况,请使用foreach循环。 and in_array() 和in_array()

sorry i if i got this wrong. 抱歉,如果我弄错了。 but doing something N times indicates using a loop 但做N次表示使用循环

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM