我对php一无所知,所以如果这对你来说很明显,请原谅我。为什么以下代码不能达到我的预期目的:
$separator = ', ';
$categories_list = 'Cat1, Cat2';
$exclude_cat = 'Cat2';
$categories_list = rtrim (str_replace( $exclude_cat, '', $categories_list ), $separator );
if ( $categories_list && $categories_list != '' ) {
echo '<br/><span class="categories-links">' . $categories_list . '</span>';
我得到的结果是Cat1,
。我希望它是Cat1
。你觉得这有什么不对吗?
谢谢
答案 0 :(得分:0)
$categories_array = explode(',', $categories_list);
$hidden_categories = array('Cat2');
foreach ($categories_array AS $category_key => $category_val) {
if (in_array($category_val, $hidden_categories) {
unset($categories_array[$category_key]);
}
}
$categories_list = implode(', ', $categories_array);
这样,你可以删除任意数量的类别,当你内爆它们时,它们将具有正确的显示格式。
另一个想法是使用REGEX去掉任何你不想要的字符。这远比前一种方法灵活得多,但它是对原始问题的更直接的答案。
// REMOVE ANYTHING THAT'S NOT A LETTER OR A NUMBER
$categories_list = preg_replace('/[^A-Z0-9]/i', '', $categories_list);
答案 1 :(得分:0)
修剪和数组在你的情况下是最好的,因为修剪避免了问题错误使函数rtrim和ltrim
PHP并且有许多用于处理数组的函数,请参阅示例:
<?php
$separator = ',';
$categories_list = 'Cat1, Cat2, Cat3, Cat4';
$categories = explode($separator, $categories_list);
$categories = array_filter($categories, 'strlen');//remove blank itens
$categories = array_map('trim', $categories);
$exclude_cat = 'Cat2';
$getKey = array_search($exclude_cat, $categories);
if(false!==$getKey){
unset($categories[$getKey]);
}
$categories = array_values($categories);
//show with loop
$j = count($categories);
for($i=0; $i<$j; ++$i){
echo $categories[$i],'<br>';
}
//show with implode
echo implode('<br>', $categories);
?>
答案 2 :(得分:-1)
谢谢大家的回答。我终于意识到它为什么不起作用(categories_list比它写入页面要多得多)...