简体   繁体   中英

PHP preg_replace help trim special characters

I tried to search around but couldn't find anything useful. I need to trim special characters from beginning and end of a string and identify if the remaining portion is a number.

For example

(5)
[[12]]
{3}
#!8(#
!255=
/879/

I need a preg_match expression for it. The regular expression should ignore the string if any alphabets come in between.

^(?!.*[a-zA-Z])\W*(\d+)\W*$

You can use this. Lookahead will validate if only numbers are there.Replace by $1 .See demo.

https://regex101.com/r/cT0hV4/2

$string="yourstring";
$new_string=preg_replace('/[^A-Za-z0-9]/', '', $string);
if(is_numeric($new_string){
    echo "number";
} else {
    echo "string";
}

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