简体   繁体   中英

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?

http://pl1.php.net/trim - that function gets characters to trim as last parameter

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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