简体   繁体   中英

Removing special Characters from start and end

I want to remove the special characters from start and end of a String.

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

This removes special characters from whole file

what I want is that if the string is 'SO@ , it should return SO

Any help?

Try this:

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
------------------------------------------------------------------------------------- */

PHP's trim function might help you, using the second argument to pass the characters you want removed. Problem is that you have to list the characters you want to removed, rather than the ones you want to keep.

trim($string,$remove);

Where $remove contains the characters you want stripped from the start and end.

We created one function and check special character for javascript

 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('');
 }  

尝试使用锚点:

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

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