如何从 php 中的字符串末尾删除特定字符

How to Remove a specific character from the end of the string in php

如何从 php

中的字符串末尾删除特定字符
$string = 'سلام-تست-است-';

我想要这样的改变

$string = 'سلام-تست-است';

在 سلام-تست-است 的末尾我们有多余的字符“-”,我想将其删除。

这是我的代码:

 foreach($tag as $t){
            $t =  str_replace(' ', '-', $t);
            if(substr($t, -1) == '-'){
              $t   = rtrim($t,"-");
            }
            $insert_value[] = '("'.$content_id.'","'.$t.'","'.time().'")';
        }

$tag 是我的字符串。 任何的想法?

由于 rtrim 如果未找到末尾的字符则什么都不做,您可以简单地 运行 它而无需 if 检查:

foreach($tag as $t) {
    $t = rtrim($t);
    $t = str_replace(' ', '-', $t);
    $insert_value[] = '("'.$content_id.'","'.$t.'","'.time().'")';
}

或者更简化为:

foreach($tag as $t) {
    $t = str_replace(' ', '-', rtrim($t));
    $insert_value[] = '("'.$content_id.'","'.$t.'","'.time().'")';
}

但是,这只是一个简化代码的提示。它也应该以问题中所示的当前形式工作,这意味着问题似乎出在其他地方。