Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/http/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 从字符串中删除特殊字符和空格_Php_Regex_Codeigniter - Fatal编程技术网

Php 从字符串中删除特殊字符和空格

Php 从字符串中删除特殊字符和空格,php,regex,codeigniter,Php,Regex,Codeigniter,我必须将帖子存储到数据库中。我想将文章标题存储为文章url,以便删除特殊字符和空格。我已经做到了。一切正常,但当我在字符串的最后给空格时,它最后显示连字符,如下所示。 Ex abcd_u1; 如果有空格,我只想删除最后一个连字符。 我已试过以下方法: function clean($post_name) { $post_name = str_replace(' ', '-', $post_name); return preg_repl

我必须将帖子存储到数据库中。我想将文章标题存储为文章url,以便删除特殊字符和空格。我已经做到了。一切正常,但当我在字符串的最后给空格时,它最后显示连字符,如下所示。
Ex abcd_u1;
如果有空格,我只想删除最后一个连字符。
我已试过以下方法:

function clean($post_name) {
               $post_name = str_replace(' ', '-', $post_name); 
               return preg_replace('/[^A-Za-z0-9\-]/', '', $post_name);
            }
            $post_url=clean($post_name);  
这怎么可能呢?
谢谢

str\u replace()

str\u replace()


要解决您的问题,这里是我的1%

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

要解决您的问题,这里是我的1%

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

尝试这样做。
trim()
函数从字符串的两侧删除空白和其他预定义字符

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); 

要了解更多信息,请尝试这样做。
trim()
函数从字符串的两侧删除空白和其他预定义字符

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); 

有关更多信息,请检查给定字符串的最后两个字符。然后指定子字符串(如果其定义正确)。您将能够在if块中输入更多的“已定义字符”进行检查

$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);

}

只需检查给定字符串的最后两个字符。然后指定子字符串(如果其定义正确)。您将能够在if块中输入更多的“已定义字符”进行检查

$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);

}

试着
trim()
就像我在回答中所说的那样试着
trim()
就像我在回答中所说的那样@这正是我想要的。非常感谢,这正是我想要的。非常感谢你