从开始和结束中删除特殊字符

时间:2014-05-27 16:00:17

标签: php regex string preg-replace

我想从字符串的开头和结尾删除特殊字符。

preg_replace('/[^a-zA-Z0-9_ %\[\]\.\(\)%&-]/s', '', $String);

这将删除整个文件中的特殊字符

我想要的是,如果字符串是'S-O @,它应该返回SO

任何帮助?

4 个答案:

答案 0 :(得分:3)

试试这个:

preg_replace( '/^\W*(.*?)\W*$/', '$1', $string )

/* -----------------------------------------------------------------------------------
  ^                        the beginning of the string
    \W*                    non-word characters (all but a-z, A-Z, 0- 9, _) (0 or more times (matching the most amount possible))
    (                      group and capture to \1:
      .*?                  any character except \n (0 or more times(matching the least amount possible))
    )                      end of \1
    \W*                    non-word characters (all but a-z, A-Z, 0-9, _) (0 or more times (matching the most amount possible))
  $                        before an optional \n, and the end of the string
------------------------------------------------------------------------------------- */

答案 1 :(得分:2)

PHP的trim函数可能会帮助您,使用第二个参数传递您想要删除的字符。问题是你必须列出你想要删除的字符,而不是你要保留的字符。

trim($string,$remove);

其中$ remove包含您想要从开头和结尾剥离的字符。

答案 2 :(得分:1)

我们创建了一个函数并检查特殊字符

 var string  = "@@@@@M@@@@U###@@";
 var output = filterSpecialChar(string);
 console.log(output); //M@@@@U

 function filterSpecialChar(string){
     var arrayString = string.split("");
     var count = arrayString.length/2;
     var check_float =  Number(count) === count && count % 1 !== 0;
     var format = /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]+/;
     if(check_float == true){
        var start_length = parseInt(count)+1;
        var end_length = parseInt(count);
     }else{
        var start_length = parseInt(count);
        var end_length = parseInt(count);
     }

        for(var i=0;i<parseInt(arrayString.length);i++){

        if(format.test(arrayString[i])){
          arrayString[i] = null; 
        }else{
            break;
        }   
    }

    for(var i=arrayString.length-1;i>0;i--){
        if(format.test(arrayString[i])){
          arrayString[i] = null; 
        }else{
            break;
        }   
    }

   var arrayString = arrayString.filter(function(data){return data != null});
   return arrayString.join('');
 }  

答案 3 :(得分:0)

尝试使用锚点:

^[^a-zA-Z0-9_ %\[\]\.\(\)%&-]|[^a-zA-Z0-9_ %\[\]\.\(\)%&-]$