简体   繁体   中英

Removing special characters and space from string

I have to stored posts to database. I want to store post title as post url, so that I need to remove special characters and spaces. I have done that. Everything is working fine but when I give space at last of the string it shows hyphen at last as follows.
Ex abcd_
I just want to remove last hyphen if there is a space.
I have tried so far as follows -

function clean($post_name) {
               $post_name = str_replace(' ', '-', $post_name); 
               return preg_replace('/[^A-Za-z0-9\-]/', '', $post_name);
            }
            $post_url=clean($post_name);  

How is this possible?
Thanks.

尝试在str_replace()之前trim() str_replace()

$post_name = str_replace(' ', '-', trim($post_name)); 

To fix your problem here is my 1%

function clean($post_name) {
    $post_name = trim($post_name);

Try like this.The trim() function removes whitespace and other predefined characters from both sides of a string.

function clean($post_name) {
               $name = trim($post_name);
               $post_name = str_replace(' ', '-', $name); 
               return preg_replace('/[^A-Za-z0-9\-]/', '', $post_name);
            }
            $post_url=clean($post_name); 

For more http://php.net/manual/en/function.trim.php

Just check the last two characters of the given string. then assign the substring if its as defined. you will be able to more "defined characters" into the if block to check.

$len = strlen($post_name)

// check if last two characters are ' -'
if ( substr($post_name, $len -2, $len) === ' -' ) {

    // assign all but the last two characters.
    $post_name = substr($post_name, 0, $len -2);

}

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