简体   繁体   English

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

[英]How to Remove a specific character from the end of the string in php or regex

I am generating a string dynamically. 我正在动态生成一个字符串。 For example The string looks like this 例如,字符串看起来像这样

$string = "this-is-a-test-string-for-example-";

It can also be like this 它也可以是这样的

$string = "this-is-a-test-string-for-example";

I want if there is a hyphen "-" at the end of the string, It should be removed. 我想如果在字符串的末尾有一个连字符"-" ,它应该被删除。 How can I do that in php or regex? 我怎么能在PHP或正则表达式中这样做?

http://pl1.php.net/trim - that function gets characters to trim as last parameter http://pl1.php.net/trim - 该函数将要修剪的字符作为最后一个参数

trim($string,"-");

or as suggested for right side only 或仅作为右侧的建议

rtrim($string,"-");

如果它总是在字符串的末尾(右侧),这将起作用

$string = rtrim($string,"-");
$cleanedString = preg_replace('/^(this-is-a-test-string-for-example)-$/', '$1', $string);
$delete = array('-');

if(in_array($string[(strlen($string)-1)], $delete))
    $string = substr($string, 0, strlen($string)-1);

You can add other characters to delete into $delete array. 您可以添加要删除的其他字符到$delete数组中。

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

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